// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// This file is part of CodingEditor.
// Note:	This project is derived from Peter Project
//			(hosted on sourceforge and codeplex)
//
// Copyright (c) 2008-2009, CE Team
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


namespace CE.Main
{
    // TODO: complete macro support, created RecordCommands utility class.
    // TODO: do complete code cleanup: remove unused methods/properties/fields from class files.

    #region Usings

    using System;
    using System.CodeDom.Compiler;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.IO;
    using System.Reflection;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Windows.Forms;
    using System.Xml;

    using CE.API;
    using CE.Classes;

    //using ICSharpCode.NRefactory;
    //using ICSharpCode.NRefactory.Ast;
    //using ICSharpCode.SharpDevelop.Dom;
    //using ICSharpCode.SharpDevelop.Dom.NRefactoryResolver;
    using ICSharpCode.TextEditor.Document;

    using Microsoft.CSharp;

    using WeifenLuo.WinFormsUI.Docking;

    #endregion

    public sealed partial class MainForm : Form, ICEPluginHost
    {
        #region Fields

        //private static readonly LanguageProperties _currentLanguageProperties =
        //        IsVisualBasic ? LanguageProperties.VBNet : LanguageProperties.CSharp;

        //internal DefaultProjectContent _myProjectContent;
        //internal ParseInformation _parseInformation;
        //internal ProjectContentRegistry _pcRegistry;
        //private ICompilationUnit _lastCompilationUnit;

        // TODO: create a new utility class to contain all main fields

        private bool _close = true;
        private IDockContent _activeContent;
        private string _activeFileType;
        private bool _loadPlugins;
        private CodeStructure _codeStructure;
        private DocViewer _docSelector;
        private Common.EditorConfig _editorConfig;
        private ErrorList _errorList;
        private Find _findControl;
        private FormState _formState;
        private HexEditor _hexEditor;
        private bool _isPluginsLoaded;
        private bool _isSyntaxFilesLoaded;
        //private Thread _parserThread;
        private cPluginCollection _plugins;
        private ProjectExplorer _projMan;
        private int _recentFileCount;
        private int _recentProjectCount;
        private bool _saveOnExit;
        private string _content = string.Empty;
        private bool _isFormatMenuLoaded = false;
        private bool _enableMacros = false;
        private bool _createNewFileOnStartUp = false;

        #endregion Fields

        //public delegate void RunExternalTool(ExternalTool tool);

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see c="CEFrmMain"/> class.
        /// </summary>
        /// <param name="args">The args.</param>
        public MainForm(string[] args)
        {
            InitializeComponent();
            Initialize();
            LoadProgramConfiguration();
            LoadDockingConfiguration();
            ParseArguments(args);
            CE.Splash.Splasher.Close();
        }

        #endregion Constructors

        #region Properties

        public static bool IsVisualBasic
        {
            get;
            set;
        }

        /// <summary>
        /// Gets the active content
        /// </summary>
        /// <value>The active content.</value>
        public IDockContent ActiveContent
        {
            get { return _activeContent; }
        }

        /// <summary>
        /// Gets or sets the active editor.
        /// </summary>
        /// <value>The active editor.</value>
        public SourceEditor ActiveEditor
        {
            get
            {
                if (_activeContent != null && _activeContent.GetType() == typeof(SourceEditor)) {
                    return (SourceEditor)_activeContent;
                }
                return null;
            }
            set { _activeContent = value; }
        }

        /// <summary>
        /// Gets the type of the active file.
        /// </summary>
        /// <value>The type of the active file.</value>
        public string ActiveFileType
        {
            get { return _activeFileType; }
        }

        /// <summary>
        /// Gets the path the Application started in...
        /// </summary>
        /// <value></value>
        public string ApplicationExeStartPath
        {
            get { return Path.GetDirectoryName(Application.ExecutablePath); }
        }

        /// <summary>
        /// Gets the Type for a Editor in string format (typeof(Editor))...
        /// </summary>
        /// <value></value>
        public string EditorType
        {
            get { return typeof(SourceEditor).ToString(); }
        }

        /// <summary>
        /// Gets the active tab.
        /// </summary>
        /// <value>The active tab.</value>
        private ICEPluginTab ActiveTab
        {
            get { return (ICEPluginTab)_activeContent; }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Adds the given Dock Content to the form...
        /// </summary>
        /// <param name="content">Content to Add.</param>
        public void AddDockContent(DockContent content)
        {
            if (CheckContent(content)) {
                content.Show(DockMain);
                content.TabPageContextMenuStrip = cmnuTab;
            }
        }

        /// <summary>
        /// Adds the given Dock Content to the form...
        /// </summary>
        /// <param name="content">Content to Add.</param>
        /// <param name="state">State of Content</param>
        public void AddDockContent(DockContent content, DockState state)
        {
            if (CheckContent(content)) {
                content.Show(DockMain, state);
                content.TabPageContextMenuStrip = cmnuTab;
            }
        }


        /// <summary>
        /// Adds the given Dock Content to the form...
        /// </summary>
        /// <param name="content">Content to Add.</param>
        /// <param name="floatingRec">Floating Rectangle</param>
        public void AddDockContent(DockContent content, Rectangle floatingRec)
        {
            if (CheckContent(content)) {
                content.Show(DockMain, floatingRec);
                content.TabPageContextMenuStrip = cmnuTab;
            }
        }

        /// <summary>
        /// Adds the given Dock Content to the form...
        /// </summary>
        /// <param name="content">Content to Add.</param>
        /// <param name="addTo">Content to Add new Tab to.</param>
        public void AddDockContent(DockContent content, IDockContent addTo)
        {
            if (CheckContent(content)) {
                content.Show(addTo.DockHandler.Pane, addTo);
                content.TabPageContextMenuStrip = cmnuTab;
            }
        }

        /// <summary>
        /// Compiles the C# code in the
        /// active editor
        /// TODO: use MSBUILD or CSC instead of using this method too limited and deprecated.
        /// </summary>
        public void CompileCSharp()
        {
            SaveCurrentFile();

            if (_errorList != null) _errorList.ClearList();

            if (ActiveTab != null && ActiveTab.GetType() == typeof(SourceEditor)) {
                if (ActiveTab.FileName != null) {
                    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
#pragma warning disable 618,612
                    ICodeCompiler icc = codeProvider.CreateCompiler();
#pragma warning restore 618,612
                    string output = Path.GetFileNameWithoutExtension(ActiveTab.TabText) + ".exe";

                    CompilerParameters parameters = new CompilerParameters {
                        GenerateExecutable = true,
                        IncludeDebugInformation = true,
                        OutputAssembly = output
                    };

                    //XmlDocument nDoc = new XmlDocument();
                    //nDoc.Load(Constants.CsNamespaceFile);
                    //XmlNodeList nodes = nDoc.GetElementsByTagName("CSharpNamespaces");
                    //if (nodes.Count == 1)
                    //    foreach (XmlNode n in nodes[0].ChildNodes)
                    //        parameters.ReferencedAssemblies.Add(n.InnerText);

                    parameters.ReferencedAssemblies.Add("System.dll");
                    parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                    //parameters.CompilerOptions = String.Concat("/lib:", @"C:\WINDOWS\Microsoft.NET\Framework\v3.5\");

                    CompilerResults results = icc.CompileAssemblyFromFile(parameters, ActiveTab.FileName);
                    if (results.Errors.Count > 0) {
                        if (null == _errorList || _errorList.IsDisposed) _errorList = new ErrorList(ActiveEditor);

                        if (!DockMain.Contents.Contains(_hexEditor)) {
                            DockContent errorListDockContent = _errorList;
                            AddDockContent(errorListDockContent, DockState.DockBottom);
                        }

                        int i = 0;
                        foreach (CompilerError error in results.Errors) {
                            int type = error.IsWarning ? 0 : 1;
                            _errorList.ShowErrors(type, error.Line.ToString(), error.Column.ToString(),
                                                 error.ErrorNumber, error.ErrorText,
                                                 Path.GetFileName(ActiveTab.FileName), i++);
                        }
                    } else {
                        Process.Start(output);
                    }
                }
            } else {
                Program.ShowMessage(Constants.TextEditorNotActive);
            }
        }

        public void CreateEditors(string[] files)
        {
            for (int i = 0; i < files.Length; i++) {
                CreateEditor(files[i], Path.GetFileName(files[i]));
            }
        }

        /// <summary>
        /// Creates a new Editor with the given file...
        /// </summary>
        /// <param name="fileName">File to load in Editor.</param>
        /// <param name="tabName">Name of Tab.</param>
        public void CreateEditor(string fileName, string tabName)
        {
            Icon fileIcon = Common.GetFileIcon(fileName, false);

            CreateEditor(fileName, tabName, fileIcon);
        }

        /// <summary>
        /// Creates a new Editor with the given file...
        /// </summary>
        /// <param name="fileName">File to load in Editor.</param>
        /// <param name="tabName">Name of Tab.</param>
        /// <param name="image">Icon for Tab.</param>
        public void CreateEditor(string fileName, string tabName, Icon image)
        {
            CreateEditor(fileName, tabName, image, null);
        }

        /// <summary>
        /// Creates a new Editor with the given file...
        /// </summary>
        /// <param name="fileName">File to load in Editor.</param>
        /// <param name="tabName">Name of Tab.</param>
        /// <param name="image">Icon for Tab.</param>
        /// <param name="addToContent">Add to Content</param>
        public void CreateEditor(string fileName, string tabName, Icon image, IDockContent addToContent)
        {
            mnuEditReformatCodeXml.Enabled = (sslModes.Text == "XML");
            FileInfo info = new FileInfo(fileName);
            if (info.Exists /*&& info.Attributes == FileAttributes.Normal*/) {
                // Add to Recent Files...
                UpdateRecentFileList(fileName);

                // Let the plugins try to load the file first...
                if (_plugins != null && _isPluginsLoaded) {
                    foreach (ICEPlugin plugin in _plugins) {
                        if (plugin.AbleToLoadFiles) {
                            if (plugin.LoadFile(fileName))
                                return;
                        }
                    }
                }

                // No plugins want the file, we can load it...
                if (!IsFileOpen(fileName)) {
                    SourceEditor e = CreateNewEditor(tabName);
                    e.ShowIcon = true;
                    e.Icon = image;
                    e.LoadFile(fileName);
                    string encoding = e.Encoding.EncodingName;
                    CheckFormatMenuItem(encoding);
                    if (_docSelector != null)
                        AddToDocSelector(Path.GetFileName(fileName));  // adds the file to DocumentSelector
                    if (addToContent == null) {
                        if (DockMain.ActiveDocumentPane != null)
                            e.Show(DockMain.ActiveDocumentPane, null);
                        else
                            e.Show(DockMain);
                    } else {
                        e.Show(addToContent.DockHandler.Pane, null);
                    }
                } else {
                    for (int a = DockMain.Contents.Count - 1; a >= 0; a--) {
                        var tab = (ICEPluginTab)DockMain.Contents[a];
                        if (tab.FileName == fileName)
                            DockMain.Contents[a].DockHandler.Show();
                    }
                }
            } else {
                Program.ShowError("Unable to open " + fileName);
            }
        }

        /// <summary>
        /// Enables the code completion.
        /// </summary>
        /// <param name="enable">if set to <c>true</c> [enable].</param>
        public void EnableCodeCompletion(bool enable)
        {
            //if (enable) {
            //    HostCallbackImplementation.Register(this);
            //    CodeCompletionKeyHandler.Attach(this, ActiveEditor.CurrentEditor);
            //    ToolTipProvider.Attach(this, ActiveEditor.CurrentEditor);

            //    _pcRegistry = new ProjectContentRegistry(); // Default .NET 2.0 registry

            //    _pcRegistry.ActivatePersistence(Path.Combine(Path.GetTempPath(),
            //                                                Constants.ProgramName));

            //    _myProjectContent = new DefaultProjectContent {
            //        Language = _currentLanguageProperties
            //    };

            //    _parserThread = new Thread(InvokeParserThread) {
            //        IsBackground = true
            //    };
            //    _parserThread.Start();
            //} else {
            //    if (_parserThread != null) {
            //        _pcRegistry = null;
            //        _myProjectContent = null;
            //        _parserThread.Abort();
            //    }
            //}
        }

        /// <summary>
        /// Changes the UI accessibility.
        /// </summary>
        /// <param name="accessible">if set to <c>true</c> [accessible].</param>
        public void ChangeUIAccessibility(bool accessible)
        {
            cmbQuickFind.Enabled =
            tsbPrintNow.Enabled =
            tsbSave.Enabled =
            tsbSaveAll.Enabled =
            tsbPaste.Enabled =
            tsbCopy.Enabled =
            tsbCut.Enabled =
            mnuSearch.Enabled = accessible;
        }

        /// <summary>
        /// Finds the in open files.
        /// </summary>
        public void FindInOpenFiles()
        {
            if (_findControl != null) {
                for (int a = 0; a < DockMain.Contents.Count; a++) {
                    var tab = (ICEPluginTab)DockMain.Contents[a];
                    if (!string.IsNullOrEmpty(tab.FileName))
                        _findControl.FindInFile(new FileInfo(tab.FileName),
                                               _findControl.FindText, _findControl.GetRegEX());
                }
            }
        }

        public bool FindNext(bool findUp)
        {
            if (ActiveContent != null && _findControl != null) {
                var tab = (ICEPluginTab)ActiveContent;
                Regex regex = _findControl.GetRegEX();
                return tab.FindNext(regex, findUp);
            }
            return false;
        }

        /// <summary>
        /// Gets the CMD.
        /// </summary>
        /// <returns></returns>
        public CommandPrompt GetCommandPrompt()
        {
            CommandPrompt cmd = null;

            foreach (IDockContent dc in DockMain.Contents) {
                if (dc.GetType() == typeof(CommandPrompt)) {
                    cmd = (CommandPrompt)dc;
                    cmd.Show();
                    break;
                }
            }
            if (cmd == null) {
                mnuToolsCommandPrompt_Click(null, null);
                cmd = (CommandPrompt)DockMain.Contents[DockMain.Contents.Count - 1];
            }

            return cmd;
        }

        /// <summary>
        /// Gets the editor containing the passed file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public SourceEditor GetEditor(string fileName)
        {
            for (int a = DockMain.Contents.Count - 1; a >= 0; a--) {
                var tab = (ICEPluginTab)DockMain.Contents[a];
                if (tab.FileName == fileName)
                    return (SourceEditor)tab;
            }

            return null;
        }

        /// <summary>
        /// Gets the Shell Icon for the given file...
        /// </summary>
        /// <param name="filePath">Path to File.</param>
        /// <param name="linkOverlay">Link Overlay or not.</param>
        /// <returns>Shell Icon for File.</returns>
        public Icon GetFileIcon(string filePath, bool linkOverlay)
        {
            return Common.GetFileIcon(filePath, linkOverlay);
        }

        /// <summary>
        /// Returns the Highlighting language name.
        /// </summary>
        /// <param name="path">Active file path</param>
        /// <returns></returns>
        public string GetHighlighterName(string path)
        {
            return ActiveEditor.Highlighting;
            //switch (Path.GetExtension(path))
            //{
            //    case ".cs":
            //        return "C#";
            //    case ".cpp":
            //    case ".h":
            //    case ".cxx":
            //    case ".cc":
            //        return "C++.NET";
            //    case ".asm":
            //        return "Assembly";
            //    default:
            //        return ".asm";
            //}
        }

        /// <summary>
        /// Loads the Configuration File...
        /// </summary>
        /// <param name="reload">Reloaded or Not.</param>
        public void LoadConfigFile(bool reload)
        {
            var xDoc = new XmlDocument();

            xDoc.Load(Constants.ConfigFile);

            // Get Editor Config...
            XmlNodeList nodes = xDoc.GetElementsByTagName("Editor");
            if (nodes.Count == 1) {
                #region -/- Parse Editor Config -\-

                foreach (XmlNode node in nodes[0].ChildNodes) {
                    switch (node.Name.ToLower()) {
                        case "showeol":
                            _editorConfig.ShowEOL = Convert.ToBoolean(node.InnerText);
                            break;
                        case "showinvalidlines":
                            _editorConfig.ShowInvalidLines = Convert.ToBoolean(node.InnerText);
                            break;
                        case "showspaces":
                            _editorConfig.ShowSpaces = Convert.ToBoolean(node.InnerText);
                            break;
                        case "showtabs":
                            _editorConfig.ShowTabs = Convert.ToBoolean(node.InnerText);
                            break;
                        case "showmatchbracket":
                            _editorConfig.ShowMatchingBracket = Convert.ToBoolean(node.InnerText);
                            break;
                        case "showlinenumbers":
                            _editorConfig.ShowLineNumbers = Convert.ToBoolean(node.InnerText);
                            break;
                        case "showhruler":
                            _editorConfig.ShowHRuler = Convert.ToBoolean(node.InnerText);
                            break;
                        case "showvruler":
                            _editorConfig.ShowVRuler = Convert.ToBoolean(node.InnerText);
                            break;
                        case "enablecodefolding":
                            _editorConfig.EnableCodeFolding = Convert.ToBoolean(node.InnerText);
                            break;
                        case "converttabs":
                            _editorConfig.ConvertTabs = Convert.ToBoolean(node.InnerText);
                            break;
                        case "useantialias":
                            _editorConfig.UseAntiAlias = Convert.ToBoolean(node.InnerText);
                            break;
                        case "allowcaretbeyondeol":
                            _editorConfig.AllowCaretBeyondEOL = Convert.ToBoolean(node.InnerText);
                            break;
                        case "highlightcurrentline":
                            _editorConfig.HighlightCurrentLine = Convert.ToBoolean(node.InnerText);
                            break;
                        case "autoinsertbracket":
                            _editorConfig.AutoInsertBracket = Convert.ToBoolean(node.InnerText);
                            break;
                        case "tabindent":
                            _editorConfig.TabIndent = Convert.ToInt32(node.InnerText);
                            break;
                        case "verticalrulercol":
                            _editorConfig.VerticalRulerCol = Convert.ToInt32(node.InnerText);
                            break;
                        case "indentstyle":
                            _editorConfig.IndentStyle = node.InnerText;
                            break;
                        case "bracketmatchingstyle":
                            _editorConfig.BracketMatchingStyle = node.InnerText;
                            break;
                        case "font":
                            string[] font = node.InnerText.Split(';');
                            var f = new Font(font[0], Convert.ToSingle(font[1]));
                            _editorConfig.EditorFont = f;
                            break;
                        case "enablecompletion":
                            _editorConfig.EnableCompletion = Convert.ToBoolean(node.InnerText);
                            break;
                        case "brackethighlightoutlinecolor":
                            if (node.InnerText.Contains(";")) {
                                string[] argb = node.InnerText.Split(';');
                                _editorConfig.BracketHighlightOutlineColor = Color.FromArgb( int.Parse(argb[0]),
                                    int.Parse(argb[1]), int.Parse(argb[2]), int.Parse(argb[3]));
                            } else {
                                _editorConfig.BracketHighlightOutlineColor = Color.FromName(node.InnerText);
                            }
                            break;
                        case "brackethighlightinnercolor":
                            if (node.InnerText.Contains(";")) {
                                string[] argb = node.InnerText.Split(';');
                                _editorConfig.BracketHighlightInnerColor = Color.FromArgb( int.Parse(argb[0]),
                                    int.Parse(argb[1]), int.Parse(argb[2]), int.Parse(argb[3]));
                            } else {
                                _editorConfig.BracketHighlightInnerColor = Color.FromName(node.InnerText);
                            }
                            break;
                    }
                }

                #endregion
            }

            // Get Application Config...
            nodes = xDoc.GetElementsByTagName("Application");
            if (nodes.Count == 1) {
                #region -/- Parse Application Config -\-

                foreach (XmlNode n in nodes[0].ChildNodes) {
                    switch (n.Name.ToLower()) {
                        case "top":
                            if (!reload)
                                Top = Convert.ToInt32(n.InnerText); break;
                        case "left":
                            if (!reload) {
                                Left = Convert.ToInt32(n.InnerText);

                                // Re-Position if off Screen...
                                int w = 0;
                                foreach (Screen screen in Screen.AllScreens)
                                    w += screen.Bounds.Width;
                                if (Left > w)
                                    Left = Left - w;
                            } break;
                        case "width":
                            if (!reload)
                                Width = Convert.ToInt32(n.InnerText); break;
                        case "height":
                            if (!reload)
                                Height = Convert.ToInt32(n.InnerText); break;
                        case "saveonexit":
                            _saveOnExit = Convert.ToBoolean(n.InnerText); break;
                        case "recentfilecount":
                            _recentFileCount = Convert.ToInt32(n.InnerText); break;
                        case "recentprojectcount":
                            _recentProjectCount = Convert.ToInt32(n.InnerText); break;
                        case "loadplugins":
                            _loadPlugins = bool.Parse(n.InnerText); break;
                        case "enablemacros":
                            _enableMacros = bool.Parse(n.InnerText); break;
                        case "createnewfile":
                            _createNewFileOnStartUp = bool.Parse(n.InnerText);
                            CreateNewDocument();
                            break;
                    }
                }

                #endregion
            }

            nodes = xDoc.GetElementsByTagName("ExternalTools");
            if (nodes.Count == 1) {
                foreach (XmlNode n in nodes[0].ChildNodes) {
                    if (n.Name.ToLower() == "tool") {
                        ExternalTools.Add(
                                n.Attributes["name"].InnerText,
                                n.Attributes["path"].InnerText,
                                n.Attributes["parameters"].InnerText);
                    }
                }
            }

            if (!reload) {
                nodes = xDoc.GetElementsByTagName("RecentProjects");
                if (nodes.Count == 1) {
                    #region -/- Parse Recent Projects -\-

                    foreach (XmlNode n in nodes[0].ChildNodes) {
                        var tsmi = new ToolStripMenuItem();
                        foreach (XmlNode nC in n.ChildNodes) {
                            if (nC.Name.ToLower() == "name")
                                tsmi.Text = nC.InnerText;
                            if (nC.Name.ToLower() == "file")
                                tsmi.Name = nC.InnerText;
                        }

                        tsmi.Click += ReopenProject;
                        mnuFileRecentProjects.DropDownItems.Add(tsmi);
                    }

                    #endregion
                }

                nodes = xDoc.GetElementsByTagName("RecentFiles");
                if (nodes.Count == 1) {
                    #region -/- Parse Recent Files -\-

                    foreach (XmlNode n in nodes[0].ChildNodes) {
                        var tsmi = new ToolStripMenuItem(n.InnerText);

                        tsmi.Click += ReopenFile;
                        mnuFileRecentFiles.DropDownItems.Add(tsmi);
                    }

                    #endregion
                }
            }

            if (reload) {
                for (int a = 0; a < DockMain.Contents.Count; a++) {
                    if (DockMain.Contents[a].GetType() == typeof(SourceEditor))
                        ((SourceEditor)DockMain.Contents[a]).SetupEditor(ref _editorConfig);
                }

                if (null != _plugins)
                    foreach (ICEPlugin plugin in _plugins)
                        plugin.ApplyOptions();
            }
        }

        /// <summary>
        /// Loads the docking configuration.
        /// </summary>
        public void LoadDockingConfiguration()
        {
            if (File.Exists(Constants.DockConfigFile))
                DockMain.LoadFromXml(Constants.DockConfigFile, GetContent);
        }

        /// <summary>
        /// Loads a Plugin...
        /// </summary>
        /// <param name="pluginPath">Full Path to Plugin</param>
        /// <returns>True if Plugin Loaded, otherwise false</returns>
        public bool LoadPlugin(string pluginPath)
        {
            if (!File.Exists(pluginPath))
                return false;

            // Just to exclude Microsoft dlls
            if (Path.GetFileNameWithoutExtension(pluginPath).Contains("Microsoft")) return true;

            Assembly asm = Assembly.LoadFile(pluginPath);
            if (asm != null) {
                Type[] types = new Type[2];

                try {
                    types = asm.GetTypes();
                } catch (ReflectionTypeLoadException ex) {
                    // TODO: LoadPlugin() catch the exception and do whatever is necessary.
                }

                foreach (Type type in types) {
                    if (type == null) continue;

                    if (type.IsAbstract)
                        continue;

                    object[] attrs = type.GetCustomAttributes(typeof(CEPluginAttribute), true);
                    if (attrs.Length > 0) {
                        if (_plugins == null) _plugins = new cPluginCollection();

                        ICEPlugin plugin = Activator.CreateInstance(type) as ICEPlugin;
                        if (plugin != null) {
                            plugin.Host = this;

                            if (!plugin.IsCompatible) {
                                Program.ShowError(plugin.Name + " is not compatible with this OS!");
                                continue;
                            }

                            if (plugin.HasMenu)
                                mnuViewPlugins.DropDownItems.Add(plugin.GetMenu());

                            if (plugin.HasTabMenu) {
                                cmnuTab.Items.Add(new ToolStripSeparator());
                                foreach (ToolStripMenuItem tsmi in plugin.GetTabMenu())
                                    cmnuTab.Items.Add(tsmi);
                            }

                            if (plugin.HasContextMenu) {
                                cmnuEditor.Items.Add(new ToolStripSeparator());
                                foreach (ToolStripMenuItem tsmi in plugin.GetContextMenu())
                                    cmnuEditor.Items.Add(tsmi);
                            }

                            _plugins.Add(plugin);
                            plugin.Start();
                        }
                    }
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// Loads the program configuration.
        /// </summary>
        public void LoadProgramConfiguration()
        {
            if (!File.Exists(Constants.ConfigFile)) {
                Program.ShowError(Constants.ConfigFileNotFound);
                this.Close();
            }
            LoadConfigFile(false);
            if (ExternalTools.Items.Count > 0) AddExternalTools();
        }


        public string LookUpProject(string word, string project)
        {
            return _projMan.LookUp(word, project);
        }

        public void MarkAll()
        {
            if (ActiveContent != null) {
                ICEPluginTab tab = (ICEPluginTab)ActiveContent;
                Regex regex = _findControl.GetRegEX();
                tab.MarkAll(regex);
            }
        }

        /// <summary>
        /// Creates a new blank editor...
        /// </summary>
        public void CreateNewDocument()
        {
            SourceEditor e = CreateNewEditor("Untitled " + SourceEditor.Count.ToString());

            sslFormat.Text = e.Encoding.EncodingName;
            e.Show(DockMain);
            //mnuEditReformatCodeXml.Enabled = false;

            // add the currently created file to the doc selector window,
            // if it's not null and disposed
            if (null != _docSelector && !_docSelector.IsDisposed)
                _docSelector.Add("Untitled " + SourceEditor.Count.ToString());
        }

        public void ReplaceAll()
        {
            if (ActiveContent != null) {
                ICEPluginTab tab = (ICEPluginTab)ActiveContent;
                Regex regex = _findControl.GetRegEX();
                string replaceText = _findControl.ReplaceText;
                tab.ReplaceAll(regex, replaceText);
            }
        }

        public void ReplaceInOpenFiles()
        {
            for (int a = 0; a < DockMain.Contents.Count; a++) {
                ICEPluginTab tab = (ICEPluginTab)DockMain.Contents[a];
                Regex regex = _findControl.GetRegEX();
                string replaceText = _findControl.ReplaceText;
                tab.ReplaceAll(regex, replaceText);
            }
        }

        public void ReplaceNext()
        {
            if (ActiveContent != null) {
                ICEPluginTab tab = (ICEPluginTab)ActiveContent;
                Regex regex = _findControl.GetRegEX();
                string replaceText = _findControl.ReplaceText;
                tab.ReplaceNext(regex, replaceText, _findControl.FindUp);
            }
        }

        /// <summary>
        /// Runs the command.
        /// </summary>
        /// <param name="command">The command.</param>
        public void RunCommand(string command)
        {
            CommandPrompt cmd = GetCommandPrompt();

            cmd.RunCommand(command);
        }

        /// <summary>
        /// Runs the script.
        /// </summary>
        /// <param name="script">The script.</param>
        /// <param name="workingDir">The working dir.</param>
        public void RunScript(string script, string workingDir)
        {
            CommandPrompt cmd = GetCommandPrompt();

            cmd.RunScript(script, workingDir);
        }

        /// <summary>
        /// Saves the Given Content As...
        /// </summary>
        /// <param name="tab">Content to Save</param>
        public void SaveAsCurrentFile(ICEPluginTab tab)
        {
            if (sfdMain.ShowDialog() == DialogResult.OK) {
                string fileName = sfdMain.FileName;
                tab.SaveAs(fileName);
            }

            UpdateTitleBar(false);
        }

        /// <summary>
        /// Selects the word.
        /// </summary>
        /// <param name="line">The line.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="wordLeng">The word length.</param>
        public void SelectWord(int line, int offset, int wordLength)
        {
            ActiveTab.SelectWord(line, offset, wordLength);
        }

        /// <summary>
        /// Writes the given text in the status bar...
        /// </summary>
        /// <param name="text">Text to Write.</param>
        public void ChangeStatus(string text)
        {
            sslMain.Text = text;
        }

        /// <summary>
        /// Updates the caret position.
        /// </summary>
        /// <param name="offset">The offset.</param>
        /// <param name="line">The line.</param>
        /// <param name="col">The col.</param>
        /// <param name="mode">The mode.</param>
        public void UpdateCaretPosition(int offset, int line, int col, string mode)
        {
            if (string.IsNullOrEmpty(mode)) {
                sslLine.Text = sslOther.Text = sslInsert.Text = sslColumn.Text = string.Empty;
            } else {
                sslLine.Text = "Ln: " + line;
                sslOther.Text = "" + mode;
                sslInsert.Text = "Offset: " + offset;
                sslColumn.Text = "Col: " + col;
            }
        }

        /// <summary>
        /// Updates the title bar.
        /// </summary>
        /// <param name="activeContentClosed">if set to <c>true</c> [active content closed].</param>
        public void UpdateTitleBar(bool activeContentClosed)
        {
            if (activeContentClosed) {
                Text = Constants.ProgramName;
            } else {
                if (DockMain.ActiveContent == null ||
                    DockMain.ActiveContent.GetType() != typeof(SourceEditor))
                    Text = Constants.ProgramName;
                else if (DockMain.ActiveContent != null &&
                         DockMain.ActiveContent.GetType() == typeof(SourceEditor))
                    Text = ((DockContent)ActiveContent).TabText + " - " + Constants.ProgramName;
            }
        }

        /// <summary>
        /// Updates the Buttons on the tool bar...
        /// </summary>
        public void UpdateToolBar()
        {
            /*this.tsbSave.Enabled = this.ActiveTab.AbleToSave;
             * this.tsbCut.Enabled = this.ActiveTab.AbleToCut;
             * this.tsbCopy.Enabled = this.ActiveTab.AbleToCopy;
             * this.tsbPaste.Enabled = this.ActiveTab.AbleToPaste;
             * this.mnuEditDelete.Enabled = this.ActiveTab.AbleToDelete;*/
        }

        /// <summary>
        /// Intercepts the Closing Action to do some clean up items...
        /// </summary>
        /// <param name="e">Cancel Events</param>
        protected override void OnClosing(CancelEventArgs e)
        {
            for (int a = DockMain.Contents.Count - 1; a >= 0; a--) {
                var tab = (ICEPluginTab)DockMain.Contents[a];
                if (tab.AbleToSave && tab.NeedsSaving) {
                    e.Cancel = !tab.CloseTab();
                    _close = !e.Cancel;
                }
            }

            if (e.Cancel == false) {
                // Save Dock Layout...
                if (_saveOnExit) {
                    DockMain.SaveAsXml(Constants.DockConfigFile);
                } else if (File.Exists(Constants.DockConfigFile)) {
                    File.Delete(Constants.DockConfigFile);
                }

                // Save Location...
                if (File.Exists(Constants.ConfigFile) && WindowState != FormWindowState.Minimized) {
                    // Load Config File...
                    var xDoc = new XmlDocument();
                    xDoc.Load(Constants.ConfigFile);
                    XmlNodeList nodes = xDoc.GetElementsByTagName("Application");
                    if (nodes.Count == 1) {
                        foreach (XmlNode n in nodes[0].ChildNodes) {
                            switch (n.Name.ToLower()) {
                                case "top":
                                    n.InnerText = Top.ToString();
                                    break;
                                case "left":
                                    n.InnerText = Left.ToString();
                                    break;
                                case "width":
                                    n.InnerText = Width.ToString();
                                    break;
                                case "height":
                                    n.InnerText = Height.ToString();
                                    break;
                                case "saveonexit":
                                    n.InnerText = _saveOnExit.ToString();
                                    break;
                            }
                        }
                    }
                    xDoc.Save(Constants.ConfigFile);
                }

                if (null != _plugins)
                    foreach (ICEPlugin plugin in _plugins)
                        plugin.Close();
                base.OnClosing(e);
            }
            Activate();
        }

        /// <summary>
        /// Checks the given content to see if it implements the ICodingEditorPluginTab Interface...
        /// </summary>
        /// <param name="content">DockContent</param>
        /// <returns>True or False</returns>
        private static bool CheckContent(DockContent content)
        {
            IList<Type> types = content.GetType().GetInterfaces();
            if (types.Contains(typeof(ICEPluginTab))) return true;
            /*foreach (Type t in types)
             * {
             *      if (t == typeof (ICodingEditorPluginTab))
             *      {
             *              return true;
             *      }
             * }*/
            Program.ShowError("Unable to Add '" + content.GetType() +
                              ".' It does not implement the ICodingEditorPluginTab Interface");
            return false;
        }

        /// <summary>
        /// Enables files to be dropped in the dock window...
        /// </summary>
        /// <param name="sender">DockPanel</param>
        /// <param name="e">Events</param>
        private static void DockMain_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
                e.Effect = DragDropEffects.All;
        }

        private void ActivateFindNext()
        {
            if (!string.IsNullOrEmpty(cmbQuickFind.Text) && cmbQuickFind.Text != "Quick Find") {
                cmbQuickFind.AutoCompleteCustomSource.Add(cmbQuickFind.Text);
                _findControl.SetFind(false);
                _findControl.FindText = cmbQuickFind.Text;
                FindNext(false);
            }
        }

        /// <summary>
        /// Adds to doc selector.
        /// </summary>
        /// <param name="file">The file.</param>
        private void AddToDocSelector(string file)
        {
            _docSelector.Add(file);
        }

        /// <summary>
        /// Adds to doc selector.
        /// </summary>
        private void AddToDocSelector()
        {
            _docSelector.Add(DockMain);
        }

        /// <summary>
        /// Changes the view mode.
        /// </summary>
        private void ChangeViewMode()
        {
            if (null == _formState) _formState = new FormState();
            mnuMain.Visible =
                    (!_formState.IsMaximized) ? !_formState.Maximize(this) : !_formState.Restore(this);
        }

        /// <summary>
        /// Checks the format menu item.
        /// </summary>
        /// <param name="encodingName">Name of the encoding.</param>
        private void CheckFormatMenuItem(string encodingName)
        {
			_content += encodingName + "\n";
			//StreamWriter writer = new StreamWriter(File.Create("EncodingNames.txt"));
			//writer.Write(_content);
			//writer.Close();
            ToolStripItem[] items = mnuFormat.DropDownItems.Find(encodingName, true);

        }

        /// <summary>
        /// Determines whether the file is already in the list.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="collection">The collection.</param>
        /// <returns>
        ///     <c>true</c> if the file is present; otherwise, <c>false</c>.
        /// </returns>
        private bool IsInToolStripItemsList(string filePath, ToolStripItemCollection collection)
        {
            for (int i = 0; i < collection.Count; ++i)
                if (collection[i].Text == filePath) return true;

            return false;
            //return collection.ContainsKey(filePath);
        }


        /// <summary>
        /// Converts the compilation unit.
        /// </summary>
        /// <param name="cu">The cu.</param>
        /// <returns></returns>
        //private ICompilationUnit ConvertCompilationUnit(INode cu)
        //{
        //    NRefactoryASTConvertVisitor converter = new NRefactoryASTConvertVisitor(_myProjectContent);

        //    cu.AcceptVisitor(converter, null);
        //    return converter.Cu;
        //}

        /// <summary>
        /// Clipboard Copy Action...
        /// </summary>
        private void Copy()
        {
            ActiveTab.Copy();
        }

        /// <summary>
        /// Creates a new Editor with the given tab Name...
        /// </summary>
        /// <param name="tabName">Name to put on tab.</param>
        /// <returns>Newly created Editor.</returns>
        private SourceEditor CreateNewEditor(string tabName)
        {
            SourceEditor e = new SourceEditor(tabName, this) {
                Host = this,
                //Icon = Icon.FromHandle(((Bitmap)GetInternalImage("newdoc")).GetHicon()),
                TabPageContextMenuStrip = cmnuTab
            };

            _activeFileType = Path.GetExtension(tabName);
            e.SetContextMenuStrip(cmnuEditor);
            e.SetupEditor(ref _editorConfig);

            return e;
        }

        /// <summary>
        /// Clipboard Cut Action...
        /// </summary>
        private void Cut()
        {
            ActiveTab.Cut();
        }

        /// <summary>
        /// Clipboard Delete Action...
        /// </summary>
        private void Delete()
        {
            ActiveTab.Delete();
        }

        /// <summary>
        /// Occurs when the Active Contents has Changed...
        /// </summary>
        /// <param name="sender">Content</param>
        /// <param name="e">Events</param>
        private void DockMain_ActiveContentChanged(object sender, EventArgs e)
        {
            //mnuLanguages.Enabled = false;
            mnuEditBookmarks.Enabled = false;
            mnuEdit.Enabled = false;
            mnuSearch.Enabled = false;

            if (DockMain.ActiveContent != null) {
                // Set the Active content...
                _activeContent = DockMain.ActiveContent;

                if (DockMain.ActiveContent.GetType() == typeof(SourceEditor)) {
                    //var edit = (SourceEditor)DockMain.ActiveContent;

                    RemoveHighlightCheckedMark();
                    mnuEditBookmarks.Enabled = true;
                    mnuEdit.Enabled = true;
                    mnuSearch.Enabled = true;
                    ActiveEditor.UpdateCaretPos();

                    if (_codeStructure != null)
                        _codeStructure.ActiveContentChanged(DockMain.ActiveContent);

                } else {
                    if (DockMain.ActiveDocument == null || DockMain.ActiveDocument.GetType() != typeof(SourceEditor)) {
                        UpdateCaretPosition(0, 0, 0, null);
                        if (_codeStructure != null)
                            _codeStructure.Clear();
                    }
                }
                if (null != _plugins)
                    foreach (ICEPlugin plugin in _plugins)
                        plugin.ActiveContentChanged(DockMain.ActiveContent);

                UpdateToolBar();
            } else {
                UpdateCaretPosition(0, 0, 0, null);
                if (_codeStructure != null)
                    _codeStructure.Clear();
            }
            UpdateTitleBar(false);
        }

        private void DockMain_ActiveDocumentChanged(object sender, EventArgs e)
        {
            if (null != DockMain.ActiveDocument) {
                if (null != DockMain.ActiveContent &&
                    DockMain.ActiveContent.GetType() == typeof(SourceEditor)) {
                    Text = ((DockContent)DockMain.ActiveDocument).TabText +
                        " - " + Constants.ProgramName;
                }
            }
        }

        /// <summary>
        /// Handles the ContentRemoved event of the DockMain control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="WeifenLuo.WinFormsUI.Docking.DockContentEventArgs"/> instance containing the event data.</param>
        private void DockMain_ContentRemoved(object sender, DockContentEventArgs e)
        {
            Type type = e.Content.GetType().GetInterface("ICEPluginTab", true); //.GetInterfaces();

            UpdateTitleBar((type != null));
        }

        /// <summary>
        /// Handles the DoubleClick event of the DockMain control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void DockMain_DoubleClick(object sender, EventArgs e)
        {
            if (_enableMacros) MacroRecordHelper.AddCommand(DockMain_DoubleClick);
            CreateNewDocument();
        }

        /// <summary>
        /// Grabs the files dropped in the Dock Window...
        /// </summary>
        /// <param name="sender">DockPanel</param>
        /// <param name="e">Events</param>
        private void DockMain_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string file in files) {
                string filePath = file;
                string tabName = Path.GetFileName(file);

                CreateEditor(filePath, tabName);
            }
        }

        /// <summary>
        /// Generates a RTF file from the current active editor.
        /// </summary>
        private void GenerateRtf()
        {
            SelectAll();
            string rtf = ICSharpCode.TextEditor.Util.RtfWriter.GenerateRtf(ActiveEditor.CurrentEditor.ActiveTextAreaControl.TextArea);
            StringBuilder file = new StringBuilder();
            file.Append(Path.GetDirectoryName(ActiveEditor.FileName));
            file.Append("\\" + Path.GetFileNameWithoutExtension(ActiveEditor.FileName) + ".rtf");
            StreamWriter writer = new StreamWriter(File.Create(file.ToString()));
            writer.Write(rtf);
            writer.Close();
        }

        /// <summary>
        /// Sets up the Content from last Session...
        /// </summary>
        /// <param name="content">Content String</param>
        /// <returns>IDockContent</returns>
        private IDockContent GetContent(string content)
        {
            // Find Results...
            if (content == typeof(FindResults).ToString()) {
                _findControl.Results.TabPageContextMenuStrip = cmnuTab;
                return _findControl.Results;
            }

            // Hex Editor
            if (content == typeof(HexEditor).ToString()) {
                var hex = new HexEditor(this) {
                    TabPageContextMenuStrip = cmnuTab
                };
                return hex;
            }

            // Clip Library
            //if (contentString == typeof(ClipLibrary).ToString())
            //{
            //    var cl = new ClipLibrary(this) { TabPageContextMenuStrip = cmnuTab };
            //    return cl;
            //}

            // ErrorList
            if (content == typeof(ErrorList).ToString()) {
                var err = new ErrorList(null) {
                    TabPageContextMenuStrip = cmnuTab
                };
                return err;
            }

            // DocumentSelector
            if (content == typeof(DocViewer).ToString()) {
                var docSel = new DocViewer(this) {
                    TabPageContextMenuStrip = cmnuTab
                };
                return docSel;
            }

            // Command Prompt...
            if (content == typeof(CommandPrompt).ToString()) {
                var cmd = new CommandPrompt(null) {
                    //Icon = Icon.FromHandle(((Bitmap)GetInternalImage("cmd")).GetHicon()),
                    TabPageContextMenuStrip = cmnuTab
                };
                return cmd;
            }

            // Code Structure...
            if (content == typeof(CodeStructure).ToString())
                return _codeStructure;

            // Editor...
            string[] pSplit = content.Split('|');
            if (pSplit.Length == 5 && pSplit[0] == typeof(SourceEditor).ToString()) {
                if (File.Exists(pSplit[2])) {
                    SourceEditor e = CreateNewEditor(pSplit[1]);
                    e.LoadFile(pSplit[2]);
                    UpdateRecentFileList(pSplit[2]);
                    // We Should'nt need to check for Duplicates...
                    e.Icon = Common.GetFileIcon(pSplit[2], false);
                    e.ScrollTo(Convert.ToInt32(pSplit[3]));
                    //e.Project = pSplit[4];
                    return e;
                }
                return CreateNewEditor(pSplit[1]);
            }

            if (pSplit.Length == 2 && pSplit[0] == typeof(ProjectExplorer).ToString()) {
                // Project Manager...
                string[] projs = pSplit[1].Split(';');
                foreach (string proj in projs)
                    OpenProject(proj);
                return _projMan;
            }

            // Plugin...
            if (_isPluginsLoaded) {
                foreach (ICEPlugin plugin in _plugins) {
                    if (plugin.CheckContentString(content)) {
                        DockContent dockContent = (DockContent)plugin.GetContent(content);
                        dockContent.TabPageContextMenuStrip = cmnuTab;
                        return dockContent;
                    }
                }
            }

            // **************************************************************************
            // TODO: DEBUG
            // If we return null, the program will crash, so just create an editor...
            return null; //CreateNewEditor("New " + CETextEditor.Count.ToString());
            // **************************************************************************
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        private void Initialize()
        {
            _isSyntaxFilesLoaded = false;
            _isPluginsLoaded = false;
            _saveOnExit = true;
            //namespaces = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + Constants.CsNamespaceFile;

            //dockConfigFile = Path.GetDirectoryName(Application.ExecutablePath) + "\\" +
            //         Constants.DockConfigFile;
            //configFile = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + Constants.ConfigFile;
            _editorConfig = new Common.EditorConfig();

            //mnuLanguages.Enabled = false;
            mnuEditBookmarks.Enabled = false;
            _activeContent = null;
            mnuEdit.Enabled = false;
            mnuSearch.Enabled = false;
            cmbQuickFind.Enabled = false;
            cmbQuickFind.Enabled = false;
            tsbPrintNow.Enabled = false;
            tsbSave.Enabled = false;
            tsbSaveAll.Enabled = false;
            tsbPaste.Enabled = false;
            tsbCopy.Enabled = false;
            tsbCut.Enabled = false;

            mnuEdit.DropDownOpening += mnuEdit_DropDownOpening;
            mnuFile.DropDownOpening += msFile_DropDownOpening;
            mnuEditReformatCodeXml.Enabled = true;

            DockMain.ShowDocumentIcon = true;
            DockMain.ActiveContentChanged += DockMain_ActiveContentChanged;
            DockMain.ContentRemoved += DockMain_ContentRemoved;
            DockMain.ActiveDocumentChanged += DockMain_ActiveDocumentChanged;
            DockMain.AllowDrop = true;
            DockMain.DragEnter += DockMain_DragEnter;
            DockMain.DragDrop += DockMain_DragDrop;

            DockMain.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor =
                    Program.DockStripStartColor;
            DockMain.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor =
                    Program.DockStripEndColor;
            DockMain.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.LinearGradientMode = LinearGradientMode.Vertical;

            DockMain.Skin.AutoHideStripSkin.DockStripGradient.StartColor = Program.DockStripEndColor;
            DockMain.Skin.AutoHideStripSkin.DockStripGradient.EndColor = Program.DockStripStartColor;
            DockMain.Skin.AutoHideStripSkin.DockStripGradient.LinearGradientMode = LinearGradientMode.Vertical;

            DockMain.Skin.AutoHideStripSkin.TabGradient.StartColor =
                    Program.AutoHideStripTabStartColor;
            DockMain.Skin.AutoHideStripSkin.TabGradient.EndColor =
                    Program.AutoHideStripTabEndColor;
            DockMain.Skin.AutoHideStripSkin.TabGradient.LinearGradientMode = LinearGradientMode.Vertical;
            DockMain.Skin.AutoHideStripSkin.TabGradient.TextColor = Color.Black;

            DockMain.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor =
                    Program.DockPaneStripActiveTabStartColor;
            DockMain.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor =
                    Program.DockPaneStripActiveTabEndColor;
            DockMain.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.LinearGradientMode
                    = LinearGradientMode.Vertical;

            DockMain.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor =
                    Program.DockPaneStripInActiveTabStartColor;
            DockMain.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor =
                    Program.DockPaneStripInActiveTabEndColor;
            DockMain.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.LinearGradientMode = LinearGradientMode.Vertical;

            Point point = new Point();
            this.tscMain.TopToolStripPanel.Join(tsMain, 0);
            point.X = tsMain.Location.X + tsMain.Width + 1;
            point.Y = tsMain.Location.Y;
            this.tscMain.TopToolStripPanel.Join(tsSearch, point);
            point.X = tsSearch.Location.X + tsSearch.Width + 1;
            this.tscMain.TopToolStripPanel.Join(tsBookmark, point);
            point.X = tsBookmark.Location.X + tsBookmark.Width + 1;
            this.tscMain.TopToolStripPanel.Join(tsRun, point);

            SetDefaultControlEvents();
        }

        private void AddExternalTools()
        {
            foreach (ExternalTool tool in ExternalTools.Items) {
                ToolStripMenuItem newMenuItem = new ToolStripMenuItem(tool.Name);
                newMenuItem.Click += ExternalTool_Clicked;
                mnuTools.DropDownItems.Add(newMenuItem);
            }
        }

        private void ExternalTool_Clicked(object sender, EventArgs e)
        {
            ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
            // - 2 because we need to ignore the separator and the setting menu item
            // in the menu items list.
            int index = mnuTools.DropDownItems.IndexOf(menuItem) - 2;
            ExternalTool tool = ExternalTools.Items[index];

            string[] arrayParams = tool.Parameters.Split('%');
            string parameters = string.Empty;
            for (int i = 0; i < arrayParams.Length; i++) {
                switch (arrayParams[i]) {
                    case "activeFile":
                        if (null != ActiveEditor && File.Exists(ActiveEditor.FileName))
                            parameters += ActiveEditor.FileName + " ";
                        break;
                }
            }
            try {
                Process.Start(tool.Path, parameters);
            } catch (FileNotFoundException ex) {
                Program.ShowError(ex.Message);
            }
        }

        /// <summary>
        /// Initializes the syntax files.
        /// </summary>
        /// <param name="sender">The sender.</param>
        private void InitializeSyntaxFiles(object sender)
        {
            if (!_isSyntaxFilesLoaded) {
                LoadSyntaxFiles();
                _isSyntaxFilesLoaded = true;
                ToolStripDropDownItem tsmiLanguages = sender as ToolStripDropDownItem;
                tsmiLanguages.ShowDropDown();
            }
        }

        /// <summary>
        /// Checks to see if a file is alread open...
        /// </summary>
        /// <param name="file">File to check.</param>
        /// <returns>True if open, else false</returns>
        private bool IsFileOpen(string file)
        {
            for (int a = 0; a < DockMain.Contents.Count; a++) {
                var tab = (ICEPluginTab)DockMain.Contents[a];
                if (file.Equals(tab.FileName,
                                StringComparison.CurrentCultureIgnoreCase)) return true;
            }
            return false;
        }

        /// <summary>
        /// Load all plugins from the plugins folder...
        /// </summary>
        private void LoadPlugins()
        {
            // if plugins folder is not in the app folder, then just return.
            if (!_loadPlugins || !Directory.Exists(Constants.PluginFolder)) return;
            
            // otherwise load all dlls into plugins array.
            string[] plugins = Directory.GetFiles(Constants.PluginFolder, "*.dll");
            foreach (string plugin in plugins) LoadPlugin(plugin);

            //TODO: void LoadPlugin(string[] plugins);
        }

        /// <summary>
        /// Loads the Highlighting Files...
        /// </summary>
        private void LoadSyntaxFiles()
        {            
            if (Directory.Exists(Constants.SyntaxFilesFolder)) {
                HighlightingManager.Manager.AddSyntaxModeFileProvider(new FileSyntaxModeProvider(Constants.SyntaxFilesFolder));
                ICollection keys = HighlightingManager.Manager.HighlightingDefinitions.Keys;
                string[] keyArray = new string[keys.Count];
                keys.CopyTo(keyArray, 0);
                Array.Sort(keyArray);
                foreach (string key in keyArray) {
                    ToolStripMenuItem tsi = new ToolStripMenuItem(key);
                    tsi.Click += ActivateNewSyntaxMode;
                    sslModes.DropDown.Items.Add(tsi);
                }
            } else {
                Program.ShowError(Constants.SyntaxFileLoadError);
            }
        }

        /// <summary>
        /// Handles the FormClosing event of the MainForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.FormClosingEventArgs"/> instance containing the event data.</param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (CLOSE)
            //    Dispose(true);
            //else
            //    e.Cancel = true;

            if (!_close) {
                e.Cancel = true;
                return;
            }
        }

        /// <summary>
        /// Displays the Open file Dialog to get files to edit...
        /// </summary>
        private void OpenExistingFile()
        {
            if (ofdMain.ShowDialog() == DialogResult.OK) {
                foreach (string file in ofdMain.FileNames) {
                    string filePath = file;
                    string tabName = Path.GetFileName(file);
                    CreateEditor(filePath, tabName);
                }
            }
        }

        /// <summary>
        /// Opens the project.
        /// </summary>
        /// <param name="fileName">Name of the project file.</param>
        private void OpenProject(string fileName)
        {
            // Is this a project file?
            if (Path.GetExtension(fileName).ToLower() == ".ceproj") {
                ShowProjectExplorer();
                // Load a Project...
                string proj = _projMan.LoadFile(fileName);

                if (proj == null)
                    // The project was already open...
                    return;

                // Add Menu Item if Needed...
                if (!mnuFileRecentProjects.DropDownItems.ContainsKey(fileName)) {
                    var tsmi = new ToolStripMenuItem(proj);
                    tsmi.Click += ReopenProject;
                    //tsmi.Tag = fileName;
                    tsmi.Name = fileName;

                    mnuFileRecentProjects.DropDownItems.Add(tsmi);
                }

                // Update Config file...
                bool inList = false;
                int count = 0;
                var xDoc = new XmlDocument();
                xDoc.Load(Constants.ConfigFile);
                XmlNodeList recent = xDoc.GetElementsByTagName("RecentProjects");
                if (recent.Count == 1) {
                    XmlNode recentNode = recent[0];
                    foreach (XmlNode n in recentNode.ChildNodes) {
                        count++;
                        foreach (XmlNode nC in n.ChildNodes) {
                            if (nC.InnerText == fileName) {
                                inList = true;
                                break;
                            }
                        }

                        if (inList) break;
                    }

                    if (!inList) {
                        if (count == _recentProjectCount)
                            // Remove the First Node...
                            recentNode.RemoveChild(recentNode.ChildNodes[0]);

                        // Add the new project...
                        XmlNode newProjectNode = xDoc.CreateNode(XmlNodeType.Element, "project", null);
                        XmlNode newFileNode = xDoc.CreateNode(XmlNodeType.Element, "file", null);
                        newFileNode.InnerText = fileName;
                        XmlNode newNameNode = xDoc.CreateNode(XmlNodeType.Element, "name", null);
                        newNameNode.InnerText = proj;
                        newProjectNode.AppendChild(newNameNode);
                        newProjectNode.AppendChild(newFileNode);
                        recentNode.AppendChild(newProjectNode);
                        xDoc.Save(Constants.ConfigFile);
                    }
                }
            }
        }

        /// <summary>
        /// Parses the arguments.
        /// </summary>
        /// <param name="args">The args.</param>
        private void ParseArguments(string[] args)
        {
            if (args.Length > 0) {
                for (short index = 0; index < args.Length; index++) {
                    Logger.WriteLog(Logger.LogLevel.Debug, args[index]);
                    if (File.Exists(args[index])) {
                        if (Path.GetExtension(args[index]).ToLower().Equals(".ceproj")) {
                            OpenProject(args[index]);
                        } else {
                            string fileName = args[index];
                            string tabName = Path.GetFileName(args[index]);
                            Icon fileIcon = Common.GetFileIcon(args[index], false);
                            CreateEditor(fileName, tabName, fileIcon);
                        }
                    }
                }
            } else {
                Logger.WriteLog(Logger.LogLevel.Debug, "No args");
            }
        }

        /// <summary>
        /// Parses the step by step.
        /// </summary>
        //private void ParseStep()
        //{
        //    try {
        //        string code = null;
        //        Invoke(new MethodInvoker(delegate
        //                                 {
        //                                     if (ActiveEditor != null)
        //                                         code = ActiveEditor.GetText();
        //                                 }));
        //        TextReader textReader = new StringReader(code ?? "");
        //        ICompilationUnit newCompilationUnit = null;
        //        SupportedLanguage supportedLanguage;

        //        switch (sslModes.Text) {
        //            case "C#":
        //                supportedLanguage = SupportedLanguage.CSharp;
        //                break;
        //            case "VBNET":
        //                supportedLanguage = SupportedLanguage.VBNet;
        //                break;
        //            default:
        //                supportedLanguage = SupportedLanguage.None;
        //                break;
        //        }

        //        using (ICSharpCode.NRefactory.IParser parser =
        //                       ParserFactory.CreateParser(supportedLanguage, textReader)) {
        //            if (parser != null) {
        //                parser.Parse();
        //                newCompilationUnit = ConvertCompilationUnit(parser.CompilationUnit);
        //            }
        //        }
        //        if (newCompilationUnit != null) {
        //            // Remove information from _lastCompilationUnit and add information from newCompilationUnit.
        //            _myProjectContent.UpdateCompilationUnit(_lastCompilationUnit, newCompilationUnit, Constants.DummyFileName);
        //            _lastCompilationUnit = newCompilationUnit;

        //            if (null == _parseInformation) _parseInformation = new ParseInformation();

        //            _parseInformation.SetCompilationUnit(newCompilationUnit);
        //        }
        //    } catch (Exception ex) {
        //        Program.ShowMessage(ex.ToString());
        //    }
        //}

        /// <summary>
        /// Invokes the parser thread.
        /// </summary>
        //private void InvokeParserThread()
        //{
        //    BeginInvoke(new MethodInvoker(delegate { sslMain.Text = "Loading mscorlib..."; }));
        //    _myProjectContent.AddReferencedContent(_pcRegistry.Mscorlib);

        //    // do one initial parser step to enable code-completion while other
        //    // erences are loading
        //    ParseStep();

        //    string[] referencedAssemblies = {
        //        "System",                "System.Data", "System.Drawing", "System.Xml", "System.Windows.Forms",
        //        "Microsoft.VisualBasic",
        //        "System.Web",            "System.Drawing"
        //    };
        //    foreach (string assemblyName in referencedAssemblies) {
        //        string assemblyNameCopy = assemblyName; // copy for anonymous method
        //        BeginInvoke(new MethodInvoker(delegate { sslMain.Text = "Loading " + assemblyNameCopy + "..."; }));
        //        IProjectContent referenceProjectContent =
        //                _pcRegistry.GetProjectContentForReference(assemblyName, assemblyName);
        //        _myProjectContent.AddReferencedContent(referenceProjectContent);
        //        if (referenceProjectContent is ReflectionProjectContent)
        //            (referenceProjectContent as ReflectionProjectContent).InitializeReferences();
        //    }
        //    if (IsVisualBasic) {
        //        _myProjectContent.DefaultImports = new DefaultUsing(_myProjectContent);
        //        _myProjectContent.DefaultImports.Usings.Add("System");
        //        _myProjectContent.DefaultImports.Usings.Add("System.Text");
        //        _myProjectContent.DefaultImports.Usings.Add("Microsoft.VisualBasic");
        //    }
        //    BeginInvoke(new MethodInvoker(delegate { sslMain.Text = "Ready"; }));

        //    // Parse the current file every 2 seconds
        //    while (!IsDisposed) {
        //        ParseStep();
        //        Thread.Sleep(2000);
        //    }
        //}

        /// <summary>
        /// Clipboard Paste Action...
        /// </summary>
        private void Paste()
        {
            ActiveTab.Paste();
        }

        /// <summary>
        /// Prints the content.
        /// </summary>
        /// <param name="showPrintDialog">if set to <c>true</c> [show print dialog].</param>
        private void PrintContent(bool showPrintDialog)
        {
            if (DockMain.Contents.Contains(ActiveEditor))
                ActiveEditor.Print(showPrintDialog);
            else
                ActiveEditor = null;
        }

        /// <summary>
        /// Edit Redo Action...
        /// </summary>
        private void Redo()
        {
            ActiveTab.Redo();
        }

        /// <summary>
        /// Removes all the Check from the Highlighting Menu...
        /// </summary>
        private void RemoveHighlightCheckedMark()
        {
            /*for (int a = 0; a < mnuLanguages.DropDown.Items.Count; a++)
             * {
             *      var tsmi = (ToolStripMenuItem) mnuLanguages.DropDown.Items[a];
             *      var tsmi1 = (ToolStripMenuItem) ctxLangs.DropDown.Items[a];
             *      tsmi.Checked = false;
             *      tsmi1.Checked = false;
             * }*/
        }

        /// <summary>
        /// Reopens the Given File...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void ReopenFile(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = sender as ToolStripMenuItem;

            if (tsmi != null) {
                string reopenFile = tsmi.Text;
                string reopenFileName = Path.GetFileName(tsmi.Text);
                CreateEditor(reopenFile, reopenFileName);
            }
        }

        /// <summary>
        /// Reopens the project.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ReopenProject(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = sender as ToolStripMenuItem;

            ShowProjectExplorer();
            // Load a Project...
            if (tsmi != null) {
                //string proj = _ProjMan.LoadFile(tsmi.Name);
            }
        }

        /// <summary>
        /// Saves all of the Contents...
        /// </summary>
        private void SaveAllOpenedFiles()
        {
            for (int a = 0; a < DockMain.Contents.Count; a++) {
                ICEPluginTab tab = (ICEPluginTab)DockMain.Contents[a];

                if (tab.FileName == null)
                    SaveAsCurrentFile(tab);
                else
                    tab.Save();
            }
        }

        /// <summary>
        /// Save the Current Pane...
        /// </summary>
        private void SaveCurrentFile()
        {
            if (ActiveTab != null) {
                if (ActiveTab.FileName == null)
                    SaveAsCurrentFile(ActiveTab);
                else
                    ActiveTab.Save();
                mnuEditReformatCodeXml.Enabled = (sslModes.Text == "XML");
                UpdateTitleBar(false);
            }
        }

        /// <summary>
        /// Select All Action...
        /// </summary>
        private void SelectAll()
        {
            ActiveTab.SelectAll();
        }

        /// <summary>
        /// Sets the events.
        /// </summary>
        private void SetDefaultControlEvents()
        {
            // File menu items
            mnuFileNewFile.Click += mnuFileNewFile_Click;
            mnuFileNewProject.Click += mnuFileNewProject_Click;
            mnuFileOpenFile.Click += mnuFileOpen_Click;
            mnuFileOpenProject.Click += mnuFileOpenProject_Click;
            mnuFileSave.Click += mnuFileSave_Click;
            mnuFileSaveAll.Click += mnuFileSaveAll_Click;
            mnuFileSaveAs.Click += mnuFileSaveAs_Click;
            mnuFileExportAsHtml.Click += mnuFileExportAsHtml_Click;
            mnuFileExportAsRtf.Click += mnuFileExportAsRtf_Click;
            mnuFilePrintPreview.Click += mnuFilePrintPreview_Click;
            mnuFilePrintDialog.Click += mnuFilePrintDialog_Click;
            mnuFilePrintNow.Click += mnuFilePrintNow_Click;
            mnuFileExit.Click += mnuFileExit_Click;

            // Edit menu items
            mnuEditUndo.Click += mnuEditUndo_Click;
            mnuEditRedo.Click += mnuEditRedo_Click;
            mnuEditCut.Click += mnuEditCut_Click;
            mnuEditDelete.Click += mnuEditDelete_Click;
            mnuEditPaste.Click += mnuEditPaste_Click;
            mnuEditCopy.Click += mnuEditCopy_Click;
            mnuEditDuplicate.Click += mnuEditDuplicate_Click;
            mnuEditSelectAll.Click += mnuEditSelectAll_Click;
            mnuEditBookmarkToggle.Click += tsbBookMark_Click;
            mnuEditBookmarkRemoveAll.Click += tsbRemBookMark_Click;
            mnuEditBookmarkNext.Click += tsbNextBkMark_Click;
            mnuEditBookmarkPrevious.Click += tsbPrBkMark_Click;
            mnuEditSplitTextArea.Click += mnuEditSplitTextArea_Click;
            mnuEditReformatCodeXml.Click += mnuEditReformatCodeXml_Click;
            mnuEditLineComment.Click += mnuEditLineComment_Click;
            mnuEditToLowerCase.Click += mnuEditToLowerCase_Click;
            mnuEditToUpperCase.Click += mnuEditToUpperCase_Click;
            mnuEditColumnEditor.Click += mnuEditColumnEditor_Click;


            // View menu items
            mnuViewPlugins.Click += mnuViewPlugins_Click;
            mnuViewFullScreeMode.Click += mnuViewFullScreenMode_Click;
            mnuViewCodeStructure.Click += mnuViewCodeStructure_Click;
            mnuViewDocViewer.Click += mnuViewDocViewer_Click;
            mnuViewHexEditor.Click += mnuViewHexEditor_Click;
            mnuViewProjectExplorer.Click += mnuViewProjectManager_Click;

            // Search menu items
            mnuSearchFind.Click += mnuSearchFind_Click;
            mnuSearchFindNext.Click += mnuSearchFindNext_Click;

            // Tools menu items
            mnuViewCommandPrompt.Click += mnuToolsCommandPrompt_Click;
            //mnuToolsNotepad.Click += mnuToolsNotepad_Click;
            mnuToolsOptions.Click += mnuToolsOptions_Click;

            // Help menu items
            mnuHelpShowAbout.Click += mnuHelpAbout_Click;
            mnuHelpCheckForUpdates.Click += mnuHelpCheckForUpdates_Click;
            mnuHelpFeatureRequest.Click += mnuHelpFeatureRequest_Click;
            mnuHelpShowLicense.Click += mnuHelpLicense_Click;
            mnuHelpProjectPage.Click += mnuHelpProjectPage_Click;
            mnuHelpReportBug.Click += mnuHelpReportBug_Click;
        }

        /// <summary>
        /// Sets the file format.
        /// </summary>
        /// <param name="format">The format.</param>
        private void SetFileFormat(Encoding format)
        {
            if (ActiveEditor != null) {
                ActiveEditor.Encoding = format;
                sslFormat.Text = format.BodyName;
            }
        }

        /// <summary>
        /// Highlighting menu selection...
        /// </summary>
        /// <param name="sender">Highlighting Menu ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void ActivateNewSyntaxMode(object sender, EventArgs e)
        {
            if (ActiveContent != null) {
                if (ActiveContent.GetType() == typeof(SourceEditor)) {
                    ToolStripItem tsmi = sender as ToolStripItem;
                    //CheckToolStripMenuItem( tsmi);
                    SourceEditor edit = (SourceEditor)ActiveContent;
                    if (tsmi != null) {
                        edit.Highlighting = tsmi.Text;
                        sslModes.Text = tsmi.Text;
                    }
                }
            }
        }

        /// <summary>
        /// Shows the code structure.
        /// </summary>
        private void ShowCodeStructure()
        {
            if (null == _codeStructure || _codeStructure.IsDisposed) {
                _codeStructure = new CodeStructure {
                    //Icon = Icon.FromHandle(((Bitmap)GetInternalImage("Code")).GetHicon()),
                    RightToLeftLayout = RightToLeftLayout
                };
            }

            if (!DockMain.Contents.Contains(_codeStructure)) {
                DockContent codeStructureDockContent = _codeStructure;
                AddDockContent(codeStructureDockContent, DockState.DockRight);
            }
        }

        /// <summary>
        /// Shows the doc viewer.
        /// </summary>
        private void ShowDocViewer()
        {
            if (null == _docSelector || _docSelector.IsDisposed)
                _docSelector = new DocViewer(this);

            if (!DockMain.Contents.Contains(_projMan)) {
                DockContent docViewerDockContent = _docSelector;
                AddDockContent(docViewerDockContent, DockState.DockLeft);
            }
            AddToDocSelector();
        }

        /// <summary>
        /// Shows the find dialog.
        /// </summary>
        private void ShowFindDialog()
        {
            // Grab the Selection...
            if (ActiveTab != null && ActiveTab.Selection.Length > 0)
                _findControl.FindText = ActiveTab.Selection;

            if (null == _findControl || _findControl.IsDisposed) {
                _findControl = new Find(this) {
                    //Icon = Icon.FromHandle(((Bitmap)GetInternalImage("Find")).GetHicon())
                };
            }

            if (!_findControl.Visible)
                _findControl.Show(this);
        }

        /// <summary>
        /// Shows the hex editor.
        /// </summary>
        private void ShowHexEditor()
        {
            if (null == _hexEditor || _hexEditor.IsDisposed)
                _hexEditor = new HexEditor(this);
            if (!DockMain.Contents.Contains(_hexEditor)) {
                DockContent hexEditorDockContent = _hexEditor;
                AddDockContent(hexEditorDockContent, DockState.Document);
            }
        }

        /// <summary>
        /// Shows the print preview window.
        /// </summary>
        private void ShowPrintPreview()
        {
            if (DockMain.Contents.Contains(ActiveEditor))
                ActiveEditor.PrintPreview();
            else
                ActiveEditor = null;
        }

        /// <summary>
        /// Shows the project manager.
        /// </summary>
        private void ShowProjectExplorer()
        {
            if (null == _projMan || _projMan.IsDisposed)
                _projMan = new ProjectExplorer(this);
            if (!DockMain.Contents.Contains(_projMan)) {
                DockContent projectManagerDockContent = _projMan;
                AddDockContent(projectManagerDockContent, DockState.DockLeft);
            }
            _projMan.TabPageContextMenuStrip = cmnuTab;
            //_projMan.Icon = Icon.FromHandle(((Bitmap)GetInternalImage("Project")).GetHicon());
        }

        /// <summary>
        /// Edit Undo Action...
        /// </summary>
        private void Undo()
        {
            ActiveTab.Undo();
        }

        /// <summary>
        /// Updates the recent file list.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        private void UpdateRecentFileList(string filePath)
        {
            bool inList = IsInToolStripItemsList(filePath, mnuFileRecentFiles.DropDownItems);

            //inList = mnuFileRecentFiles.DropDownItems.ContainsKey(filePath);
            if (inList) return;

            ToolStripMenuItem newTSMI = new ToolStripMenuItem(filePath);
            newTSMI.Click += ReopenFile;
            mnuFileRecentFiles.DropDownItems.Add(newTSMI);

            // Update Config file
            int count = 0;
            var xDoc = new XmlDocument();
            xDoc.Load(Constants.ConfigFile);
            XmlNodeList recent = xDoc.GetElementsByTagName("RecentFiles");
            if (recent.Count == 1) {
                XmlNode recentNode = recent[0];
                foreach (XmlNode n in recentNode.ChildNodes) {
                    count++;
                    if (n.InnerText == ofdMain.FileName) {
                        inList = true;
                        break;
                    }
                }

                if (!inList) {
                    if (count == _recentFileCount)
                        // Remove the First Node...
                        recentNode.RemoveChild(recentNode.ChildNodes[0]);

                    // Add the new file...
                    XmlNode newFileNode = xDoc.CreateNode(XmlNodeType.Element, "file", null);
                    newFileNode.InnerText = filePath;
                    recentNode.AppendChild(newFileNode);
                    xDoc.Save(Constants.ConfigFile);
                }
            }
        }

        /// <summary>
        /// Updates UI accessibilty
        /// </summary>
        /// <param name="index">an unique number which identifies a set of controls.</param>
        private void UpdateUIAccessibility(int index)
        {
            switch (index) {
                case 1: // File Menu
			    {
					if (ActiveTab != null)
						mnuFileSave.Enabled = mnuFileSaveAs.Enabled = ActiveTab.AbleToSave;
					else
						mnuFileSave.Enabled = mnuFileSaveAs.Enabled = false;
                } break;
                case 2: // Edit Menu
			    {
					if (ActiveContent != null) {
						mnuEditCut.Enabled = ((ActiveTab.Selection.Length > 0) && ActiveTab.AbleToCut);
						mnuEditCopy.Enabled = ((ActiveTab.Selection.Length > 0) && ActiveTab.AbleToCopy);
						mnuEditDelete.Enabled = ((ActiveTab.Selection.Length > 0) && ActiveTab.AbleToDelete);
						mnuEditPaste.Enabled = ActiveTab.AbleToPaste;
						mnuEditRedo.Enabled = ActiveTab.AbleToRedo;
						mnuEditUndo.Enabled = ActiveTab.AbleToUndo;
						mnuEditSelectAll.Enabled = ActiveTab.AbleToSelectAll;
					} else {
						mnuEditCut.Enabled = mnuEditCopy.Enabled = mnuEditDelete.Enabled = false;
						mnuEditPaste.Enabled = false;
						mnuEditRedo.Enabled = false;
						mnuEditUndo.Enabled = false;
						mnuEditSelectAll.Enabled = false;
					}
                } break;
            }
        }

        /// <summary>
        /// If the keydown in comboBox is enter key,
        /// then search for the text in the editor.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbQuickFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                tsbFind_Click(null, null);
        }

        /// <summary>
        /// Copys the path of the Current Document...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void copyPathToolStripMenuIte_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ActiveTab.FileName))
                Clipboard.SetText(ActiveTab.FileName);
        }

        /// <summary>
        /// Closes the Current Document...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void ctxClose_Click(object sender, EventArgs e)
        {
            if (DockMain.ActivePane.ActiveContent.ToString() == "CE.Main.SourceEditor")
                ActiveTab.CloseTab();
            else
                DockMain.ActivePane.CloseActiveContent();
        }

        /// <summary>
        /// Closes all but the Current Document...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void ctxCloseAllBut_Click(object sender, EventArgs e)
        {
            CloseTab(false, string.Empty, true);
        }

        /// <summary>
        /// Closes all opened texteditor tabs.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctxCloseAll_Click(object sender, EventArgs e)
        {
            CloseTab(false, "CE.Main.SourceEditor", false);
        }


        /// <summary>
        /// Closes the tab.
        /// !! TO DEBUG !!
        /// </summary>
        /// <param name="closeAll">if set to <c>true</c> [close all].</param>
        /// <param name="objectToString">if closeAll set to false and excludeActiveTab set to false,
        /// then all objects containing this parameter in their string reprentation will be closed.</param>
        /// <param name="excludeActiveTab">if set to <c>true</c> exclude active tab from being closed.</param>
        /// 
        /// Close all tabs of type SourceEditor:
        ///     CloseTab(false, "CE.Main.SourceEditor", false);
        ///     
        /// Close all tabs but not the active one:
        ///     CloseTab(false, "", true);
        /// 
        /// Close all tabs:
        ///     CloseTab(true, "", false);  if closeAll is set to true, other params are 
        ///                                 ignored
        /// 
        private void CloseTab(bool closeAll, string objectToString, bool excludeActiveTab)
        {
            for (int index = DockMain.Contents.Count - 1; index >= 0; index--) {
                if (closeAll) {
                    DockMain.Contents[index].DockHandler.Close(); 
                } else if (objectToString != string.Empty) {
                    if (DockMain.Contents[index].ToString().Contains(objectToString)) {
                            DockMain.Contents[index].DockHandler.Close();
                    }
                } else if (excludeActiveTab) {
                    if (DockMain.Contents[index] != ActiveTab)
                        DockMain.Contents[index].DockHandler.Close();
                }
            }
        }

        /// <summary>
        /// Clipboard Copy Action...
        /// </summary>
        /// <param name="sender">ToolStirpMenuItem</param>
        /// <param name="e">Events</param>
        private void ctxCopy_Click(object sender, EventArgs e)
        {
            Copy();
        }

        /// <summary>
        /// Clipboard Cut Action...
        /// </summary>
        /// <param name="sender">ToolStirpMenuItem</param>
        /// <param name="e">Events</param>
        private void ctxCut_Click(object sender, EventArgs e)
        {
            Cut();
        }

        /// <summary>
        /// Clipboard Delete Action...
        /// </summary>
        /// <param name="sender">ToolStirpMenuItem</param>
        /// <param name="e">Events</param>
        private void ctxDelete_Click(object sender, EventArgs e)
        {
            Delete();
        }

        /// <summary>
        /// Action before Editor Menu Opens...
        /// </summary>
        /// <param name="sender">Editor Context Menu</param>
        /// <param name="e">Events</param>
        private void ctxEditor_Opening(object sender, CancelEventArgs e)
        {
            cmnuEditorCut.Enabled = ((ActiveTab.Selection.Length > 0) && ActiveTab.AbleToCut);
            cmnuEditorCopy.Enabled = ((ActiveTab.Selection.Length > 0) && ActiveTab.AbleToCopy);
            cmnuEditorDelete.Enabled = ((ActiveTab.Selection.Length > 0) && ActiveTab.AbleToDelete);
            cmnuEditorPaste.Enabled = (Clipboard.ContainsText() && ActiveTab.AbleToPaste);
            cmnuEditorRedo.Enabled = ActiveTab.AbleToRedo;
            cmnuEditorUndo.Enabled = ActiveTab.AbleToUndo;
            cmnuEditorSelectAll.Enabled = ActiveTab.AbleToSelectAll;
        }

        /// <summary>
        /// Handles the Click event of the ctxLangs control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ctxLangs_Click(object sender, EventArgs e)
        {
            InitializeSyntaxFiles(sender);
        }

        /// <summary>
        /// Clipboard Paste Action...
        /// </summary>
        /// <param name="sender">ToolStirpMenuItem</param>
        /// <param name="e">Events</param>
        private void ctxPaste_Click(object sender, EventArgs e)
        {
            Paste();
        }

        /// <summary>
        /// Edit Redo Action...
        /// </summary>
        /// <param name="sender">ToolStirpMenuItem</param>
        /// <param name="e">Events</param>
        private void ctxRedo_Click(object sender, EventArgs e)
        {
            Redo();
        }

        /// <summary>
        /// Handles the Click event of the ctxSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ctxSave_Click(object sender, EventArgs e)
        {
            SaveCurrentFile();
        }

        /// <summary>
        /// Selects All Text in the Current Document...
        /// </summary>
        /// <param name="sender">ToolStirpMenuItem</param>
        /// <param name="e">Events</param>
        private void ctxSelectAll_Click(object sender, EventArgs e)
        {
            SelectAll();
        }

        /// <summary>
        /// Event Before Tab Context Menu is opened
        /// </summary>
        /// <param name="sender">Tab Context Menu Strip</param>
        /// <param name="e">Events</param>
        private void ctxTab_Opening(object sender, CancelEventArgs e)
        {
            cmnuTabCopyPath.Enabled =
                    cmnuTabOpenContainingFolder.Enabled = (ActiveTab.FileName != null);
        }

        /// <summary>
        /// Edit Undo Action...
        /// </summary>
        /// <param name="sender">ToolStirpMenuItem</param>
        /// <param name="e">Events</param>
        private void ctxUndo_Click(object sender, EventArgs e)
        {
            Undo();
        }

        /// <summary>
        /// Handles the FormClosing event of the e control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void e_FormClosing(object sender, EventArgs e)
        {
            var tab = (ICEPluginTab)DockMain.ActiveDocument;

            if (tab.GetType() == typeof(SourceEditor))
                tab.CloseTab();
        }

        /// <summary>
        /// Finds the Next Occurance of the given Pattern
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void findInFilesToolStripMenuIte_Click(object sender, EventArgs e)
        {
            HandleFindInFilesTSMClick();
        }

        private void HandleFindInFilesTSMClick()
        {
            // Set Dialog for Find...
            ShowFindDialog();
            _findControl.SetFind(true);
        }


        private void findPreviousToolStripMenuIte_Click(object sender, EventArgs e)
        {
            FindNext(true);
        }

        /// <summary>
        /// Goes to the next book mark on the active editor...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuBookmarkNext_Click(object sender, EventArgs e)
        {
            Bookmark();
        }

        private void Bookmark()
        {
            if (ActiveEditor != null)
                ActiveEditor.GotoMark(true);
        }

        /// <summary>
        /// Goes to the Previous book mark on the active editor...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuBookMarkPrevious_Click(object sender, EventArgs e)
        {
            if (ActiveEditor != null)
                ActiveEditor.GotoMark(false);
        }

        /// <summary>
        /// Removes all book marks on the active editor...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuBookMarkRemoveAll_Click(object sender, EventArgs e)
        {
            if (ActiveEditor != null)
                ActiveEditor.RemoveAllMarks();
        }

        /// <summary>
        /// Toggles a book mark on the active editor...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuBookMarkToggle_Click(object sender, EventArgs e)
        {
            if (ActiveEditor != null)
                ActiveEditor.ToggleMark();
        }

        private void mnuEditColumnEditor_Click(object sender, EventArgs e)
        {
            //ColumnEditor columnEditorForm = new ColumnEditor(ActiveEditor);
            //columnEditorForm.Show();
            new ColumnEditor(ActiveEditor).Show();
        }

        /// <summary>
        /// Clipboard Copy Action...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuEditCopy_Click(object sender, EventArgs e)
        {
            Copy();
        }

        /// <summary>
        /// Clipboard Cut Action...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuEditCut_Click(object sender, EventArgs e)
        {
            Cut();
        }

        /// <summary>
        /// Clipboard Delete Action...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuEditDelete_Click(object sender, EventArgs e)
        {
            Delete();
        }

        /// <summary>
        /// Duplicates the current selection...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuEditDuplicate_Click(object sender, EventArgs e)
        {
            ActiveTab.Duplicate();
        }

        private void mnuEditLineComment_Click(object sender, EventArgs e)
        {
            ActiveEditor.MakeLineComment();
        }

        /// <summary>
        /// Clipboard Paste Action...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuEditPaste_Click(object sender, EventArgs e)
        {
            Paste();
        }

        /// <summary>
        /// Edit Redo Action...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuEditRedo_Click(object sender, EventArgs e)
        {
            Redo();
        }

        /// <summary>
        /// Handles the Click event of the mnuEditReformatCodeXml control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuEditReformatCodeXml_Click(object sender, EventArgs e)
        {
            FormatXmlCode();
        }

        // **************************************************************************
        /// <summary>
        /// Formats the XML code in the active editor.
        /// </summary>
        private void FormatXmlCode()
        {
            if (ActiveEditor == null) return;
            //will hold formatted xml
            var sb = new StringBuilder();
            //does the formatting
            XmlTextWriter xtw = null;
            try {
                /*
                 *      & - &amp;
                 *      < - &lt;
                 *      > - &gt;
                 *      " - &quot;
                 *      ' - &#39;
                 */
                string xml = ActiveEditor.GetText();
                xml = xml.Replace("&", "&amp;");

                //load unformatted xml into a dom
                var xd = new XmlDocument();
                xd.LoadXml(xml);

                //pumps the formatted xml into the StringBuilder above
                var sw = new StringWriter(sb);

                //point the xtw at the StringWriter
                xtw = new XmlTextWriter(sw) {
                    Formatting = Formatting.Indented,
                    Indentation = 4
                };

                //we want the output formatted

                //get the dom to dump its contents into the xtw
                xd.WriteTo(xtw);
            } catch (Exception ex) {
                MessageBox.Show(this, "Error while parsing XML.\n" + ex.Message, Constants.ProgramName, MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            } finally {
                //clean up even if error
                if (xtw != null)
                    xtw.Close();
            }

            //return the formatted xml
            if (!string.IsNullOrEmpty(sb.ToString()))
                ActiveEditor.SetTextChanged(sb.ToString().Replace("&amp;", "&"));
        }

        // **************************************************************************

        /// <summary>
        /// Selects All of the Text in the Current Document...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuEditSelectAll_Click(object sender, EventArgs e)
        {
            SelectAll();
        }

        /// <summary>
        /// Enables or disables Split view to the active editor
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnuEditSplitTextArea_Click(object sender, EventArgs e)
        {
            if (mnuEditSplitTextArea.Checked) {
                mnuEditSplitTextArea.Checked = false;
                ActiveEditor.Split();
            } else {
                mnuEditSplitTextArea.Checked = true;
                ActiveEditor.Split();
            }
        }

        /// <summary>
        /// Converts selected text to Lowercase, if not selected, all text will be converted to
        /// Lowercase.</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnuEditToLowerCase_Click(object sender, EventArgs e)
        {
            ActiveEditor.ToLowerCase();
        }

        /// <summary>
        /// Converts selected text to Uppercase, if not selected, all text will be converted to
        /// Uppercase.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnuEditToUpperCase_Click(object sender, EventArgs e)
        {
            ActiveEditor.ToUpperCase();
        }

        /// <summary>
        /// Edit Undo Action...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuEditUndo_Click(object sender, EventArgs e)
        {
            Undo();
        }

        /// <summary>
        /// Action before Edit Menu Opens...
        /// </summary>
        /// <param name="sender">Edit Menu</param>
        /// <param name="e">Events</param>
        private void mnuEdit_DropDownOpening(object sender, EventArgs e)
        {
            UpdateUIAccessibility(2);
        }

        /// <summary>
        /// Exits the Program
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuFileExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// Exports the active file to HTML, with syntax highlighting
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnuFileExportAsHtml_Click(object sender, EventArgs e)
        {
            ExportAsHtml();
        }

        private void ExportAsHtml()
        {
            SaveCurrentFile();
            if (ActiveTab != null) {
                if (ActiveTab.FileName != null) {
                    var hw = new HtmlWriter { ShowLineNumbers = true };
                    string code = File.ReadAllText(ActiveTab.FileName);
                    string html = hw.GenerateHtml(code, GetHighlighterName(ActiveTab.FileName));
                    File.WriteAllText(Path.GetFileNameWithoutExtension(ActiveTab.FileName) + ".html",
                                      "<html><body>" + html + "</body></html>");
                    Process.Start(Path.GetFileNameWithoutExtension(ActiveTab.FileName) + ".html");
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the mnuFileExportAsRtf control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuFileExportAsRtf_Click(object sender, EventArgs e)
        {
            ExportAsRtf();
        }

        private void ExportAsRtf()
        {
            // No active editor, return!
            if (ActiveEditor == null) return;

            GenerateRtf();
        }

        /// <summary>
        /// Creates a new Blank Editor...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuFileNewFile_Click(object sender, EventArgs e)
        {
            if (_enableMacros) MacroRecordHelper.AddCommand(mnuFileNewFile_Click);
            CreateNewDocument();
            if (_docSelector != null) AddToDocSelector();
        }

        /// <summary>
        /// Handles the Click event of the mnuFileNewProject control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuFileNewProject_Click(object sender, EventArgs e)
        {
            /* Project prj = new Project();
             * prj.ShowDialog();
             * if (prj.ProjectFile != null)
             * {
             *       OpenProject(prj.ProjectFile);
             * }
             * if (!prj.IsDisposed)
             * {
             *       prj.Close();
             * }
             */
            using (NewProject project = new NewProject()) {
                project.ShowDialog();
            }
        }

        /// <summary>
        /// Handles the Click event of the mnuFileOpenProject control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuFileOpenProject_Click(object sender, EventArgs e)
        {
            ofdMain.Multiselect = false;
            ofdMain.Filter = Constants.ProjectFileFilter;
            if (ofdMain.ShowDialog() == DialogResult.OK)
                OpenProject(ofdMain.FileName);
            ofdMain.Multiselect = true;
            ofdMain.Filter = string.Empty;
        }

        /// <summary>
        /// Opens a Documnet...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuFileOpen_Click(object sender, EventArgs e)
        {
            OpenExistingFile();
        }

        /// <summary>
        /// Handles the Click event of the mnuFilePrintDialog control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuFilePrintDialog_Click(object sender, EventArgs e)
        {
            PrintContent(true);
        }

        /// <summary>
        /// Handles the Click event of the mnuFilePrintNow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuFilePrintNow_Click(object sender, EventArgs e)
        {
            PrintContent(false);
        }

        /// <summary>
        /// Handles the Click event of the mnuFilePrintPreview control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuFilePrintPreview_Click(object sender, EventArgs e)
        {
            ShowPrintPreview();
        }

        /// <summary>
        /// Saves all of the Open Documents...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuFileSaveAll_Click(object sender, EventArgs e)
        {
            SaveAllOpenedFiles();
        }

        /// <summary>
        /// Save the Current Document As...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuFileSaveAs_Click(object sender, EventArgs e)
        {
            SaveAsCurrentFile((ICEPluginTab)ActiveContent);
        }

        /// <summary>
        /// Save the Current Document...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuFileSave_Click(object sender, EventArgs e)
        {
            SaveCurrentFile();
        }

        /// <summary>
        /// Shows the About Form...
        /// </summary>
        /// <param name="sender">ToolStipMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuHelpAbout_Click(object sender, EventArgs e)
        {
            ShowAboutForm();
        }

        private static void ShowAboutForm()
        {
            using (About about = new About()) {
                about.ShowDialog();
            }
        }

        /// <summary>
        /// Checks for a new version of CodingEditor
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnuHelpCheckForUpdates_Click(object sender, EventArgs e)
        {
            ShowUpdateChecker();
        }

        private void ShowUpdateChecker()
        {
            using (UpdateChecker uc = new UpdateChecker()) {
                if (uc.IsSuccessfulXmlFileParse)
                    uc.ShowDialog();
            }
        }

        /// <summary>
        /// Handles the Click event of the mnuHelpFeatureRequest control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuHelpFeatureRequest_Click(object sender, EventArgs e)
        {
            Program.FeatureRequest();
        }

        /// <summary>
        /// Opens the program license file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnuHelpLicense_Click(object sender, EventArgs e)
        {
            Process.Start("notepad", Constants.LicenseFile);
        }

        /// <summary>
        /// Navigate to CodingEditor's sourceforge website page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnuHelpProjectPage_Click(object sender, EventArgs e)
        {
            Process.Start(Constants.ProjectPage);
        }

        /// <summary>
        /// Handles the Click event of the mnuHelpReportBug control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuHelpReportBug_Click(object sender, EventArgs e)
        {
            Program.ReportBugs();
        }

        /// <summary>
        /// Finds the Next Occurance of the given Pattern
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuSearchFindNext_Click(object sender, EventArgs e)
        {
            FindNext(false);
        }

        /// <summary>
        /// Activates the Find Dialog...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void mnuSearchFind_Click(object sender, EventArgs e)
        {
            // Set Dialog for Find...
            ShowFindDialog();
            _findControl.SetFind(false);
        }

        /// <summary>
        /// Handles the Click event of the mnuSearchReplace control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuSearchReplace_Click(object sender, EventArgs e)
        {
            ShowFindDialog();
            _findControl.SetReplace(false);
        }

        /// <summary>
        /// Handles the Click event of the mnuToolsCommandPrompt control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuToolsCommandPrompt_Click(object sender, EventArgs e)
        {
            ShowCommandPrompt();
        }

        /// <summary>
        /// Shows the command prompt.
        /// </summary>
        private void ShowCommandPrompt()
        {
            ICEPluginTab tab = (ICEPluginTab)DockMain.ActiveDocument;
            CommandPrompt cmd;

            if (tab != null && tab.GetType() == typeof(SourceEditor))
                cmd = new CommandPrompt(Path.GetDirectoryName(tab.FileName));
            else
                cmd = new CommandPrompt(null);

            //cmd.Icon = Icon.FromHandle(((Bitmap)GetInternalImage("cmd")).GetHicon());
            DockContent cmdDockContent = cmd;
            AddDockContent(cmdDockContent, DockState.DockBottomAutoHide);
        }

        /// <summary>
        /// Handles the Click event of the mnuToolsNotepad control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuToolsNotepad_Click(object sender, EventArgs e)
        {
            ShowNotepad();
        }

        private void ShowNotepad()
        {
        }

        /// <summary>
        /// Handles the Click event of the mnuToolsPerences control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuToolsOptions_Click(object sender, EventArgs e)
        {
            ShowOptionsForm();
        }

        private void ShowOptionsForm()
        {
            using (Options options = new Options(this)) {
                options.ShowDialog();
            }
        }

        /// <summary>
        /// Handles the Click event of the mnuViewCodeStructure control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuViewCodeStructure_Click(object sender, EventArgs e)
        {
            ShowCodeStructure();
        }

        /// <summary>
        /// Handles the Click event of the mnuViewDocViewer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuViewDocViewer_Click(object sender, EventArgs e)
        {
            ShowDocViewer();
        }

        /// <summary>
        /// Handles the Click event of the mnuViewFullScreenMode control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuViewFullScreenMode_Click(object sender, EventArgs e)
        {
            ChangeViewMode();
        }

        // **************************************************************************
        //private void clipLibraryToolStripMenuIte_Click(object sender, EventArgs e)
        //{
        //    if (null == _clipLibrary || _clipLibrary.IsDisposed)
        //        _clipLibrary = new ClipLibrary(this);
        //    if (!DockMain.Contents.Contains(_clipLibrary))
        //    {
        //        DockContent clipLibraryDockContent = _clipLibrary;
        //        AddDockContent( clipLibraryDockContent, DockState.DockRight);
        //    }
        //}
        // **************************************************************************

        /// <summary>
        /// Handles the Click event of the mnuViewHexEditor control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuViewHexEditor_Click(object sender, EventArgs e)
        {
            ShowHexEditor();
        }

        /// <summary>
        /// Handles the Click event of the mnuViewProjectManager control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuViewProjectManager_Click(object sender, EventArgs e)
        {
            ShowProjectExplorer();
        }

        /// <summary>
        /// Handles the Click event of the mnuView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuViewPlugins_Click(object sender, EventArgs e)
        {
            if (_loadPlugins) {
                LoadPlugins();
                mnuView.ShowDropDown();
                mnuViewPlugins.ShowDropDown();
                _loadPlugins = false;
            }
        }

        /// <summary>
        /// Action before File Menu Opens...
        /// </summary>
        /// <param name="sender">File Menu</param>
        /// <param name="e">Events</param>
        private void msFile_DropDownOpening(object sender, EventArgs e)
        {
            UpdateUIAccessibility(1);
        }

        /// <summary>
        /// Opens the Folder containing the Current Document...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void openFolderToolStripMenuIte_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ActiveTab.FileName))
                Process.Start("explorer.exe",
                              "/select," + ActiveTab.FileName);
        }

        /// <summary>
        /// Handles the Click event of the replaceInFilesToolStripMenuIte control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void replaceInFilesToolStripMenuIte_Click(object sender, EventArgs e)
        {
            ShowFindDialog();
            _findControl.SetReplace(true);
        }

        /// <summary>
        /// Handles the Click event of the replaceNextToolStripMenuIte control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void replaceNextToolStripMenuIte_Click(object sender, EventArgs e)
        {
            ReplaceNext();
        }

        /// <summary>
        /// Saves the Current Document...
        /// </summary>
        /// <param name="sender">ToolStripMenuItem</param>
        /// <param name="e">Events</param>
        private void saveToolStripMenuIte_Click(object sender, EventArgs e)
        {
            SaveCurrentFile();
        }

        /// <summary>
        /// Handles the TextChanged event of the sslMode control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void sslMode_TextChanged(object sender, EventArgs e)
        {
            //if (sslModes.Text != "C#" && sslModes.Text != "VBNET")
            //    DisableCodeCompletion();
            //else
            //    EnableCodeCompletion();

            // same as above
            EnableCodeCompletion(
                    _editorConfig.EnableCompletion
                //sslModes.Text == "C#" || sslModes.Text == "VBNET"
                    );
        }

        /// <summary>
        /// Handles the Click event of the sslModes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void sslModes_Click(object sender, EventArgs e)
        {
            if (!_isSyntaxFilesLoaded) InitializeSyntaxFiles(sender);
        }

        /// <summary>
        /// Bookmark the current line
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbBookMark_Click(object sender, EventArgs e)
        {
            mnuBookMarkToggle_Click(null, null);
        }

        /// <summary>
        /// Compile C# Code
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbCompileAndRun_Click(object sender, EventArgs e)
        {
            switch (_activeFileType) {
                case ".cs": CompileCSharp(); break;
                case ".c":
                case ".cpp": break;
            }
        }

        /// <summary>
        /// Clipboard Copy Action...
        /// </summary>
        /// <param name="sender">ToolStripButton</param>
        /// <param name="e">Events</param>
        private void tsbCopy_Click(object sender, EventArgs e)
        {
            Copy();
        }

        /// <summary>
        /// Clipboard Cut Action...
        /// </summary>
        /// <param name="sender">ToolStripButton</param>
        /// <param name="e">Events</param>
        private void tsbCut_Click(object sender, EventArgs e)
        {
            Cut();
        }

        /// <summary>
        /// Handles the Click event of the tsbFind control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void tsbFind_Click(object sender, EventArgs e)
        {
            ActivateFindNext();
        }

        /// <summary>
        /// Creates a new Blank Editor...
        /// </summary>
        /// <param name="sender">ToolStripButton</param>
        /// <param name="e">Events</param>
        private void tsbNew_Click(object sender, EventArgs e)
        {
            if (_enableMacros) MacroRecordHelper.AddCommand(tsbNew_Click);
            CreateNewDocument();
        }

        /// <summary>
        /// Move to next bookmark
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbNextBkMark_Click(object sender, EventArgs e)
        {
            mnuBookmarkNext_Click(null, null);
        }

        /// <summary>
        /// Opens a Documnet...
        /// </summary>
        /// <param name="sender">ToolStripButton</param>
        /// <param name="e">Events</param>
        private void tsbOpen_Click(object sender, EventArgs e)
        {
            OpenExistingFile();
        }

        /// <summary>
        /// Clipboard Paste Action...
        /// </summary>
        /// <param name="sender">ToolStripButton</param>
        /// <param name="e">Events</param>
        private void tsbPaste_Click(object sender, EventArgs e)
        {
            Paste();
        }

        /// <summary>
        /// Move to previous bookmark
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbPrBkMark_Click(object sender, EventArgs e)
        {
            mnuBookMarkPrevious_Click(null, null);
        }

        /// <summary>
        /// Prints the Active Content...
        /// </summary>
        /// <param name="sender">ToolStripButton</param>
        /// <param name="e">Events</param>
        private void tsbPrint_Click(object sender, EventArgs e)
        {
            if (null != ActiveTab)
                ActiveTab.Print(false);
        }

        /// <summary>
        /// Edit Redo Action...
        /// </summary>
        /// <param name="sender">ToolStripButton</param>
        /// <param name="e">Events</param>
        private void tsbRedo_Click(object sender, EventArgs e)
        {
            Redo();
        }

        /// <summary>
        /// Removes all bookmarks from the editor
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbRemBookMark_Click(object sender, EventArgs e)
        {
            mnuBookMarkRemoveAll_Click(null, null);
        }

        /// <summary>
        /// Saves all of the Open Documents...
        /// </summary>
        /// <param name="sender">ToolStripButton</param>
        /// <param name="e">Events</param>
        private void tsbSaveAll_Click(object sender, EventArgs e)
        {
            SaveAllOpenedFiles();
        }

        /// <summary>
        /// Save the Current Document...
        /// </summary>
        /// <param name="sender">ToolStripButton</param>
        /// <param name="e">Events</param>
        private void tsbSave_Click(object sender, EventArgs e)
        {
            SaveCurrentFile();
        }

        /// <summary>
        /// Edit Undo Action...
        /// </summary>
        /// <param name="sender">ToolStripButton</param>
        /// <param name="e">Events</param>
        private void tsbUndo_Click(object sender, EventArgs e)
        {
            Undo();
        }

        /// <summary>
        /// Handles the KeyDown event of the txtFindNext control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param>
        private void txtFindNext_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                tsbFind_Click(null, null);
        }

        /// <summary>
        /// Handles the Click event of the mnuFileOpenFolder control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void mnuFileOpenFolder_Click(object sender, EventArgs e)
        {
            OpenFilesFromFolder();
        }

        /// <summary>
        /// Opens all files from a folder.
        /// </summary>
        private void OpenFilesFromFolder()
        {
            using (FolderBrowserDialog folderBrowser = new FolderBrowserDialog()) {
                if (folderBrowser.ShowDialog() == DialogResult.OK) {
                    string[] files = Directory.GetFiles(folderBrowser.SelectedPath, "*.*", SearchOption.AllDirectories);
                    if (files.Length > 0) {
                        CreateEditors(files);
                    }
                }
            }
        }


        protected override void WndProc(ref Message m)
        {
            switch (m.Msg) {
                case Constants.W_COPYDATA: // 0x004A:    // WM_COPYDATA
                    CopyDataStruct str = (CopyDataStruct)System.Runtime.InteropServices.Marshal.PtrToStructure(m.LParam,
                        typeof(CopyDataStruct));
                    string[] files = str.LpData.Split('|');
                    foreach (string file in files) {
                        if (!string.IsNullOrEmpty(file) && File.Exists(file)) {
                            CreateEditor(file, Path.GetFileName(file), Common.GetFileIcon(file, false));
                        }
                    } break;
            }
            base.WndProc(ref m);
        }

        private void mnuMacroRecord_Click(object sender, EventArgs e)
        {
            _enableMacros = true;
            MacroRecordHelper.ClearAll();
            mnuMacroRecord.Enabled = false;
            mnuMacroStopRecording.Enabled = true;
        }

        private void mnuMacroStopRecording_Click(object sender, EventArgs e)
        {
            _enableMacros = false;
            mnuMacroStopRecording.Enabled = false;
            mnuMacroRecord.Enabled = true;
            mnuMacroPlay.Enabled = MacroRecordHelper.Commands.Count > 0;
            mnuMacroClearLastMacro.Enabled = MacroRecordHelper.Commands.Count > 0;
            mnuMacroSaveLastMacro.Enabled = MacroRecordHelper.Commands.Count > 0;
        }

        private void mnuMacroPlay_Click(object sender, EventArgs e)
        {
            // TODO: Specify a more informational message for macro play error
            if (!MacroRecordHelper.TryPlay()) Program.ShowError("Macro play error!");
        }

        private void mnuMacroClearLastMacro_Click(object sender, EventArgs e)
        {
            MacroRecordHelper.ClearAll();
            mnuMacroRecord.Enabled = true;
            mnuMacroStopRecording.Enabled = false;
            mnuMacroPlay.Enabled = false;
            mnuMacroClearLastMacro.Enabled = false;
            mnuMacroSaveLastMacro.Enabled = false;
        }

        private void mnuMacroSaveLastMacro_Click(object sender, EventArgs e)
        {
            ShowSaveMacroDialog();
        }

        private void ShowSaveMacroDialog()
        {
            using (SaveMacro frmSaveMacro = new SaveMacro()) {
                frmSaveMacro.Location = MousePosition;
                frmSaveMacro.ShowDialog();
            }
        }

        #endregion Methods

        
        #region move it to the settings window

        private void mnuFormat_Click(object sender, EventArgs e)
        {
            if (!_isFormatMenuLoaded) {
                LoadFormatMenuItems();
            }
        }

        private void LoadFormatMenuItems()
        {
            EncodingInfo[] encodings = Encoding.GetEncodings();
            for (int index = 0; index < encodings.Length; index++ ) {
                ToolStripMenuItem menuItem = new ToolStripMenuItem(encodings[index].DisplayName);
                menuItem.Name = "mnuFormat" + encodings[index].Name;
                menuItem.Click += ChangeFileEncoding;
                mnuFormat.DropDownItems.Add(menuItem);
            }
            _isFormatMenuLoaded = true;
        }

        private void ChangeFileEncoding(object sender, EventArgs e)
        {
            ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
            Encoding encoding = Encoding.GetEncoding(menuItem.Name.Substring(9));
            SetFileFormat(encoding);
        }

        #endregion

        #region Other

        /// <summary>
        /// Gets an Image from the InternalImages resource file...
        /// </summary>
        /// <param name="imageName">Name of Image</param>
        /// <returns>Image</returns>
        //public Image GetInternalImage(string imageName)
        //{
        //    var mngr = new ResourceManager("CodingEditor.InternalImages", GetType().Assembly);
        //    return (Image)mngr.GetObject(imageName);
        //}

         
         

        #endregion Other
    }
}